Contenido:
El objetivo de esta tarea es clasificar una extracto de una escena Sentinel 2 usando el clasificadores de machine learning Random Forest.
En primer lugar, cargamos los paquetes que se vamos a emplear en esta tarea:
library(sp)
library(rgdal)
library(raster)
library(reshape)
library(grid)
library(gridExtra)
library(RStoolbox)
library(caret)
library(rasterVis)
library(corrplot)
library(doParallel)
library(NeuralNetTools)
library(tidyr)
library(stringr)
library(e1071)
library(sf)
library (mapview)
El siguiente paso consistirá en definir el directorio de trabajo donde se localizarán nuestras imágenes. Los datos se corresponden con una escena Sentinel 2 (fichero denominado sentinel_o_bxx.tif, siendo xx el número de la banda)
setwd("C:/Geoforest/Tec_Clasif")
dir_in_o<-"./Material_practicas/Sentinel/O"
dir_in_p<-"./Material_practicas/Sentinel/P"
dir_in_v<-"./Material_practicas/Sentinel/V"
A continuación, creamos una lista con los nombres de los archivos alojados en el directorio de trabajo, y posteriormente un rasterstack para las escenas de otoño (o), primavera (p) y verano (v):
rasList_o <- list.files(dir_in_o,pattern="tif",
full.names = TRUE)
sentinel_o <- stack(rasList_o)
rasList_p <- list.files(dir_in_p,pattern="tif",
full.names = TRUE)
sentinel_p <- stack(rasList_p)
rasList_v <- list.files(dir_in_v,pattern="tif",
full.names = TRUE)
sentinel_v <- stack(rasList_v)
Una vez generado, vamos a proceder a comprobar los atributos de la escena
sentinel_o
## class : RasterStack
## dimensions : 2052, 2057, 4220964, 10 (nrow, ncol, ncell, nlayers)
## resolution : 20, 20 (x, y)
## extent : 300920, 342060, 4042100, 4083140 (xmin, xmax, ymin, ymax)
## crs : +proj=utm +zone=30 +datum=WGS84 +units=m +no_defs
## names : sentinel_o_b01, sentinel_o_b02, sentinel_o_b03, sentinel_o_b04, sentinel_o_b05, sentinel_o_b06, sentinel_o_b07, sentinel_o_b08, sentinel_o_b09, sentinel_o_b10
## min values : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
## max values : 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535
sentinel_p
## class : RasterStack
## dimensions : 2052, 2057, 4220964, 10 (nrow, ncol, ncell, nlayers)
## resolution : 20, 20 (x, y)
## extent : 300920, 342060, 4042100, 4083140 (xmin, xmax, ymin, ymax)
## crs : +proj=utm +zone=30 +datum=WGS84 +units=m +no_defs
## names : sentinel_p_b01, sentinel_p_b02, sentinel_p_b03, sentinel_p_b04, sentinel_p_b05, sentinel_p_b06, sentinel_p_b07, sentinel_p_b08, sentinel_p_b09, sentinel_p_b10
## min values : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
## max values : 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535
sentinel_v
## class : RasterStack
## dimensions : 2052, 2057, 4220964, 10 (nrow, ncol, ncell, nlayers)
## resolution : 20, 20 (x, y)
## extent : 300920, 342060, 4042100, 4083140 (xmin, xmax, ymin, ymax)
## crs : +proj=utm +zone=30 +datum=WGS84 +units=m +no_defs
## names : sentinel_v_b01, sentinel_v_b02, sentinel_v_b03, sentinel_v_b04, sentinel_v_b05, sentinel_v_b06, sentinel_v_b07, sentinel_v_b08, sentinel_v_b09, sentinel_v_b10
## min values : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
## max values : 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535
A continuación, se van a generar los gráficos de densidad e histogramas. Esto puede hacer individualmente para cada una de las bandas:
gdensidad=ggplot(sentinel_o,aes(sentinel_o_b01))+geom_density()
ghistograma=ggplot(sentinel_o,aes(sentinel_o_b01))+geom_histogram()
print (gdensidad)
print (ghistograma)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
O de todas las bandas, generando un gráfico por cada una de ellas y posteriormente componerlos en una sola figura
#Escena Otoño
gdens1=ggplot(sentinel_o,aes(sentinel_o_b01))+geom_density()
gdens2=ggplot(sentinel_o,aes(sentinel_o_b02))+geom_density()
gdens3=ggplot(sentinel_o,aes(sentinel_o_b03))+geom_density()
gdens4=ggplot(sentinel_o,aes(sentinel_o_b04))+geom_density()
gdens5=ggplot(sentinel_o,aes(sentinel_o_b05))+geom_density()
gdens6=ggplot(sentinel_o,aes(sentinel_o_b06))+geom_density()
gdens7=ggplot(sentinel_o,aes(sentinel_o_b07))+geom_density()
gdens8=ggplot(sentinel_o,aes(sentinel_o_b08))+geom_density()
gdens9=ggplot(sentinel_o,aes(sentinel_o_b09))+geom_density()
gdens10=ggplot(sentinel_o,aes(sentinel_o_b10))+geom_density()
grid.arrange(gdens1,gdens2,gdens3,gdens4,gdens5,gdens6,gdens7,gdens8,gdens9,gdens10,ncol=4,nrow=4)
#Escena Primavera (teniendo grabada la imagen anterior, vamos a sobreescribir para no cargar en exceso el entorno de trabajo)
gdens1=ggplot(sentinel_p,aes(sentinel_p_b01))+geom_density()
gdens2=ggplot(sentinel_p,aes(sentinel_p_b02))+geom_density()
gdens3=ggplot(sentinel_p,aes(sentinel_p_b03))+geom_density()
gdens4=ggplot(sentinel_p,aes(sentinel_p_b04))+geom_density()
gdens5=ggplot(sentinel_p,aes(sentinel_p_b05))+geom_density()
gdens6=ggplot(sentinel_p,aes(sentinel_p_b06))+geom_density()
gdens7=ggplot(sentinel_p,aes(sentinel_p_b07))+geom_density()
gdens8=ggplot(sentinel_p,aes(sentinel_p_b08))+geom_density()
gdens9=ggplot(sentinel_p,aes(sentinel_p_b09))+geom_density()
gdens10=ggplot(sentinel_p,aes(sentinel_p_b10))+geom_density()
grid.arrange(gdens1,gdens2,gdens3,gdens4,gdens5,gdens6,gdens7,gdens8,gdens9,gdens10,ncol=4,nrow=4)
#Escena Verano
gdens1=ggplot(sentinel_v,aes(sentinel_v_b01))+geom_density()
gdens2=ggplot(sentinel_v,aes(sentinel_v_b02))+geom_density()
gdens3=ggplot(sentinel_v,aes(sentinel_v_b03))+geom_density()
gdens4=ggplot(sentinel_v,aes(sentinel_v_b04))+geom_density()
gdens5=ggplot(sentinel_v,aes(sentinel_v_b05))+geom_density()
gdens6=ggplot(sentinel_v,aes(sentinel_v_b06))+geom_density()
gdens7=ggplot(sentinel_v,aes(sentinel_v_b07))+geom_density()
gdens8=ggplot(sentinel_v,aes(sentinel_v_b08))+geom_density()
gdens9=ggplot(sentinel_v,aes(sentinel_v_b09))+geom_density()
gdens10=ggplot(sentinel_v,aes(sentinel_v_b10))+geom_density()
grid.arrange(gdens1,gdens2,gdens3,gdens4,gdens5,gdens6,gdens7,gdens8,gdens9,gdens10,ncol=4,nrow=4)
Vamos a limpiar el entorno de trabajo una vez analizada y guardada la información:
remove(gdens1,gdens2,gdens3,gdens4,gdens5,gdens6,gdens7,gdens8,gdens9,gdens10)
Al ser una clasificación supervisada necesitaremos aportar al clasificador la información necesaria para realizar las fases de entrenamiento y validación. Para ello, tenemos descargado previamiente nuestro MFE con geometría poligonal, lo que nos ofrece dos opciones a la hora de continuar:
Opción 1: Preparación de los datos desde un software externo, por ejemplo QGIS, y luego leerlo en R.
Opción 2: Preparación de los datos desde R.
En nuestro caso se trabajará con la segunda opción. Para ello, comenzamos generando una semilla para garantizar la repetitividad de los resultados. Seguidamente llamaremos a nuestro shapefile del MFE.
set.seed(123)
MFE=st_read('./Material_practicas/MFE/MFE.shp')
## Reading layer `MFE' from data source
## `C:\Geoforest\Tec_Clasif\Material_practicas\MFE\MFE.shp' using driver `ESRI Shapefile'
## Simple feature collection with 22 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: 310927.3 ymin: 4052098 xmax: 332056.3 ymax: 4073143
## Projected CRS: ETRS89 / UTM zone 30N
mapview (MFE,zcol='leyenda')
Con objeto de obtener una muestra balanceada, se va a determinar el total de la superficie ocupada por cada clase de la leyenda, repartiendo el tamaño de la muestra proporcional a la superficie ocupada.
clases = unique(MFE$leyenda)
area_total = sum(st_area(MFE))
area_clases=0
for (i in 1:length(clases)) {
geom_clase=MFE[which(MFE$leyenda == clases[i],arr.ind=FALSE),]
area_clases[i]=sum(st_area(geom_clase))
}
Fijamos un tamaño total de muestreo igual a 500 puntos de tal forma que cada clase contenga el siguiente número de muestras:
num_muestras= as.integer(500*area_clases/area_total)
print(num_muestras)
## [1] 28 0 26 6 0 0 15 0 25 36 122 34 203
Observamos que no hay muestras en todas las clases, que hay clases con un número elevado y otras en las que el número es muy reducido o directamente cero.
Aun sabiendo que no es correcto, en lugar de establecer el muestreo atendiendo al criterio anterior vamos a seleccionar un número fijo de muestras para todas las clases. Posteriormente, se determinará una leyenda adecuada a la variabilidad espacial y espectral de las clases presentes en la escena.
Procedemos pues a realizar un muestreo sobre el MFE de tipo aleatorio, extrayendo la información temática a partir de la función st_join.
puntos.ref <- st_sample(MFE, c(50,50,50,50,50,50,50,50,50,50,50,50,50), type='random',exact=TRUE) #Generamos una lista de puntos de forma aleatoria
puntos.ref<-st_sf(puntos.ref) #Convertimos la lista en un spatial feature
puntos.ref<-st_join(puntos.ref,MFE) #Cruzamos los datos
puntos.ref_backup <- puntos.ref
mapview(puntos.ref, zcol='leyenda')
Veamos su representación sobre el MFE:
mapview(MFE, zcol='leyenda')+mapview(puntos.ref,zcol='leyenda')
A continuación, obtenemos la firma espectral de cada una de las clases. Para ello es necesario extraer los valores de reflectancia para cada punto en cada una de las bandas mediante el comando extract. Seguidamente, se determinarán los valores medios de reflectancia por clase y banda. Estos datos los representaremos mediante la librería ggplot , convirtiéndolos a un tipo de dato dataframe.
puntos.ref=as_Spatial(puntos.ref)
puntos.ref@data$leyenda=as.factor(puntos.ref@data$leyenda)
reflectancia_o<- as.data.frame(raster::extract(sentinel_o,puntos.ref))
reflectancia_p<- as.data.frame(raster::extract(sentinel_p,puntos.ref))
reflectancia_v<- as.data.frame(raster::extract(sentinel_v,puntos.ref))
Comprobamos los valores extraidos:
head(reflectancia_o)
## sentinel_o_b01 sentinel_o_b02 sentinel_o_b03 sentinel_o_b04 sentinel_o_b05
## 1 935 701 434 684 1405
## 2 1069 871 703 985 2058
## 3 869 562 356 456 800
## 4 875 583 360 454 843
## 5 922 681 469 694 1312
## 6 929 696 471 702 1611
## sentinel_o_b06 sentinel_o_b07 sentinel_o_b08 sentinel_o_b09 sentinel_o_b10
## 1 1705 1545 1754 689 340
## 2 2270 2263 2531 1983 1174
## 3 962 787 883 497 258
## 4 853 901 1032 755 333
## 5 1720 1605 1697 1248 698
## 6 1998 1923 2179 1293 633
head(reflectancia_p)
## sentinel_p_b01 sentinel_p_b02 sentinel_p_b03 sentinel_p_b04 sentinel_p_b05
## 1 888 766 576 842 1607
## 2 879 774 607 949 1903
## 3 797 657 452 674 1560
## 4 812 647 417 637 1653
## 5 826 674 463 761 1453
## 6 832 703 497 767 1594
## sentinel_p_b06 sentinel_p_b07 sentinel_p_b08 sentinel_p_b09 sentinel_p_b10
## 1 1785 1756 1922 1127 618
## 2 2197 2237 2383 1706 955
## 3 1783 1800 2040 1176 612
## 4 1993 1968 2119 1181 547
## 5 1666 1675 1839 1246 643
## 6 1890 1795 1975 1472 788
head(reflectancia_v)
## sentinel_v_b01 sentinel_v_b02 sentinel_v_b03 sentinel_v_b04 sentinel_v_b05
## 1 868 779 573 834 1511
## 2 933 849 768 998 1533
## 3 920 844 797 997 1506
## 4 873 783 632 899 1685
## 5 870 756 627 866 1446
## 6 871 776 650 900 1552
## sentinel_v_b06 sentinel_v_b07 sentinel_v_b08 sentinel_v_b09 sentinel_v_b10
## 1 1739 1642 1902 1007 487
## 2 1811 1736 1984 1746 997
## 3 1716 1676 1961 1406 792
## 4 2013 1972 2204 1436 640
## 5 1649 1678 1925 1404 736
## 6 1820 1755 1976 1540 802
A continuación, calculamos el valor medio de reflectancia de cada clase para cada banda. Para ello, usaremos la función aggregate() para unir los puntos de entrenamiento por clase.
mean_reflectancia_o <-aggregate(reflectancia_o,list(puntos.ref$leyenda),mean,na.rm = TRUE)
mean_reflectancia_p <-aggregate(reflectancia_p,list(puntos.ref$leyenda),mean,na.rm = TRUE)
mean_reflectancia_v <-aggregate(reflectancia_v,list(puntos.ref$leyenda),mean,na.rm = TRUE)
Comprobamos los valores medios obtenidos
head(mean_reflectancia_o)
## Group.1 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## 1 Algarrobos 1088.940 954.56 782.28
## 2 Bosques Mixtos 1040.033 842.18 704.48
## 3 Cadufolios 1348.460 1171.52 1135.10
## 4 Castaños/Caducifolios 1105.320 954.24 1059.78
## 5 Eucalipto 926.980 672.34 475.60
## 6 Matorral 1460.080 1292.59 1219.90
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## 1 1126.10 2144.880 2429.600 2449.42 2619.32
## 2 910.86 1535.053 1722.407 1719.52 1846.22
## 3 1327.40 1725.660 1868.640 1904.24 2057.20
## 4 1233.26 1441.640 1580.820 1616.80 1753.70
## 5 629.52 1082.500 1208.240 1133.80 1279.34
## 6 1449.83 2027.840 2184.040 2173.93 2315.40
## sentinel_o_b09 sentinel_o_b10
## 1 1576.540 945.54
## 2 1255.907 784.16
## 3 1897.600 1326.12
## 4 2244.360 1609.96
## 5 784.000 439.12
## 6 1613.840 1137.70
head(mean_reflectancia_p)
## Group.1 sentinel_p_b01 sentinel_p_b02 sentinel_p_b03
## 1 Algarrobos 975.8400 909.18 760.7400
## 2 Bosques Mixtos 981.1467 885.00 799.7667
## 3 Cadufolios 1205.8600 1141.88 1128.9600
## 4 Castaños/Caducifolios 1204.5000 1250.70 1431.7000
## 5 Eucalipto 883.3600 751.06 582.2600
## 6 Matorral 1127.4100 1076.54 1028.9900
## sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07 sentinel_p_b08
## 1 1117.70 2009.660 2294.940 2295.44 2468.160
## 2 1055.14 1733.807 1942.313 1934.74 2088.953
## 3 1397.74 1959.420 2166.840 2220.58 2415.540
## 4 1684.24 2091.260 2273.300 2272.56 2425.560
## 5 841.22 1549.340 1764.960 1713.40 1912.860
## 6 1300.50 1915.880 2112.820 2124.43 2288.230
## sentinel_p_b09 sentinel_p_b10
## 1 1641.420 1013.80
## 2 1662.413 1072.12
## 3 2575.320 1857.42
## 4 2654.740 1930.00
## 5 1298.580 754.36
## 6 1976.590 1401.48
head(mean_reflectancia_v)
## Group.1 sentinel_v_b01 sentinel_v_b02 sentinel_v_b03
## 1 Algarrobos 1039.0600 1027.30 1013.60
## 2 Bosques Mixtos 995.8467 954.56 944.60
## 3 Cadufolios 1187.9400 1202.16 1338.54
## 4 Castaños/Caducifolios 1017.3800 1037.66 1059.72
## 5 Eucalipto 935.0600 859.70 796.78
## 6 Matorral 1135.7600 1138.94 1175.06
## sentinel_v_b04 sentinel_v_b05 sentinel_v_b06 sentinel_v_b07 sentinel_v_b08
## 1 1254.08 1921.700 2227.780 2147.78 2464.500
## 2 1152.58 1671.693 1897.693 1844.30 2083.993
## 3 1521.96 1965.040 2230.100 2203.12 2536.360
## 4 1272.80 2116.960 2532.440 2481.18 2779.380
## 5 1014.26 1614.720 1869.980 1818.96 2067.880
## 6 1381.01 1855.160 2079.810 2021.26 2299.120
## sentinel_v_b09 sentinel_v_b10
## 1 1785.84 1068.200
## 2 1688.32 1021.873
## 3 2666.94 1727.560
## 4 1945.90 1150.180
## 5 1440.50 793.820
## 6 2044.84 1351.780
Por la forma en la que estan almacenados los datos en el dataframe (cada banda se almacena en una columna) es necesario modificarlo para que esten todos los datos de reflectancias registrados en una columna, creando una nueva columna donde se registre la banda de donde proceden, de tal forma que la información aparecerá ordenada por filas.
mean_reflectance2_o <- gather(mean_reflectancia_o, key="banda", value="reflectance",sentinel_o_b01:sentinel_o_b10)
mean_reflectance2_p <- gather(mean_reflectancia_p, key="banda", value="reflectance",sentinel_p_b01:sentinel_p_b10)
mean_reflectance2_v <- gather(mean_reflectancia_v, key="banda", value="reflectance",sentinel_v_b01:sentinel_v_b10)
Si analizamos el contenido del dataframe vemos que no se dispone de un campo numérico que permita ordenar las bandas a la hora de pintarlas. Por ello se va a crear un nuevo campo de tipo numérico con el número de la banda.
mean_reflectance2_o$banda_num=(as.numeric(str_replace(mean_reflectance2_o$banda,"sentinel_o_b","")))
mean_reflectance2_p$banda_num=(as.numeric(str_replace(mean_reflectance2_p$banda,"sentinel_p_b","")))
mean_reflectance2_v$banda_num=(as.numeric(str_replace(mean_reflectance2_v$banda,"sentinel_v_b","")))
Finalmente, mediante ggplot generamos un gráfico de tipo geom_line para ver la firma espectral de cada una de clases.
#Escena Otoño
ggplot(mean_reflectance2_o,aes(x=banda_num,y=reflectance))+
geom_line(aes(colour = Group.1))+theme_bw()
#Escena Primavera
ggplot(mean_reflectance2_p,aes(x=banda_num,y=reflectance))+
geom_line(aes(colour = Group.1))+theme_bw()
#Escena Verano
ggplot(mean_reflectance2_v,aes(x=banda_num,y=reflectance))+
geom_line(aes(colour = Group.1))+theme_bw()
Observamos que muchas de las clases presentan un comportamiento muy similar y por tanto la calidad temática de los resultados de la clasificación a priori pueden ser baja. Por ello, habría que modificar la leyenda: En esta tarea se ofrece un ejemplo de modificación de leyenda que requiere revisión, como confirman los resultados de la clasificación
MFE <- cbind(MFE, Leyenda2=c("Quercineas", "Algarrobos", "Veg. Dispersa", "Veg. Dispersa", "Veg. Dispersa","Caducifolios", "Veg. Ribera", "Castaños","Quercineas", "Matorral", "Eucalipto", "Bosque Coniferas", "Bosques Mixtos", "Bosques Mixtos", "Bosques Mixtos", "Bosque Coniferas","Bosque Coniferas","Bosque Coniferas","Bosque Coniferas", "Pinsapos", "Matorral", "Suelos"))
#Comprobamos y después eliminamos la columna de leyenda previa
MFE$leyenda <- NULL
head(MFE)
## Simple feature collection with 6 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension: XY
## Bounding box: xmin: 314177.5 ymin: 4053430 xmax: 332009.8 ymax: 4073075
## Projected CRS: ETRS89 / UTM zone 30N
## OBJECTID NOM_FORARB
## 1 1 Alcornocales
## 2 2 Algarrobales
## 3 3 Arbolado disperso de coníferas
## 4 4 Arbolado disperso coníferas y frondosas
## 5 5 Arbolado disperso de frondosas
## 6 6 Bosques mixtos de frondosas en region biogeográfica mediterranea
## Shape_Leng Shape_Area Leyenda2 geometry
## 1 34046.308 4419618.87 Quercineas MULTIPOLYGON (((327097.1 40...
## 2 2555.562 72156.21 Algarrobos MULTIPOLYGON (((320255.1 40...
## 3 71051.972 7422134.73 Veg. Dispersa MULTIPOLYGON (((329848.7 40...
## 4 18064.940 1223076.86 Veg. Dispersa MULTIPOLYGON (((330778.8 40...
## 5 25784.370 2122003.75 Veg. Dispersa MULTIPOLYGON (((331059 4055...
## 6 27104.844 2580524.10 Caducifolios MULTIPOLYGON (((327256.8 40...
Visualizamos el nuevo mapa:
set.seed(123)
mapview (MFE,zcol='Leyenda2')
Determinamos el total de la superficie ocupada por cada clase de la leyenda, repartiendo el tamaño de la muestra proporcional a la superficie ocupada:
clases = unique(MFE$Leyenda2)
area_total = sum(st_area(MFE))
area_clases=0
for (i in 1:length(clases)) {
geom_clase=MFE[which(MFE$Leyenda2 == clases[i],arr.ind=FALSE),]
area_clases[i]=sum(st_area(geom_clase))
}
Fijamos un tamaño total de muestreo igual a 500 puntos de tal forma que cada clase contenga el siguiente número de muestras:
num_muestras= as.integer(500*area_clases/area_total)
print(num_muestras)
## [1] 28 0 26 6 0 0 15 0 147 36 34 203
De nuevo, seleccionamos un número fijo de muestras para todas las clases.
puntos.ref <- st_sample(MFE, c(50,50,50,50,50,50,50,50,50,50,50,50,50), type='random',exact=TRUE) #Generamos una lista de puntos de forma aleatoria
puntos.ref<-st_sf(puntos.ref) #Convertimos la lista en un spatial feature
puntos.ref<-st_join(puntos.ref,MFE) #Cruzamos los datos
puntos.ref_backup <- puntos.ref
mapview(puntos.ref, zcol='Leyenda2')
Veamos su representación sobre el MFE:
mapview(MFE, zcol='Leyenda2')+mapview(puntos.ref,zcol='Leyenda2')
Obtenemos la firma espectral de cada una de las clases.
puntos.ref=as_Spatial(puntos.ref)
puntos.ref@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
reflectancia_o<- as.data.frame(raster::extract(sentinel_o,puntos.ref))
reflectancia_p<- as.data.frame(raster::extract(sentinel_p,puntos.ref))
reflectancia_v<- as.data.frame(raster::extract(sentinel_v,puntos.ref))
Comprobamos los valores extraidos:
head(reflectancia_o)
## sentinel_o_b01 sentinel_o_b02 sentinel_o_b03 sentinel_o_b04 sentinel_o_b05
## 1 935 701 434 684 1405
## 2 1069 871 703 985 2058
## 3 869 562 356 456 800
## 4 875 583 360 454 843
## 5 922 681 469 694 1312
## 6 929 696 471 702 1611
## sentinel_o_b06 sentinel_o_b07 sentinel_o_b08 sentinel_o_b09 sentinel_o_b10
## 1 1705 1545 1754 689 340
## 2 2270 2263 2531 1983 1174
## 3 962 787 883 497 258
## 4 853 901 1032 755 333
## 5 1720 1605 1697 1248 698
## 6 1998 1923 2179 1293 633
head(reflectancia_p)
## sentinel_p_b01 sentinel_p_b02 sentinel_p_b03 sentinel_p_b04 sentinel_p_b05
## 1 888 766 576 842 1607
## 2 879 774 607 949 1903
## 3 797 657 452 674 1560
## 4 812 647 417 637 1653
## 5 826 674 463 761 1453
## 6 832 703 497 767 1594
## sentinel_p_b06 sentinel_p_b07 sentinel_p_b08 sentinel_p_b09 sentinel_p_b10
## 1 1785 1756 1922 1127 618
## 2 2197 2237 2383 1706 955
## 3 1783 1800 2040 1176 612
## 4 1993 1968 2119 1181 547
## 5 1666 1675 1839 1246 643
## 6 1890 1795 1975 1472 788
head(reflectancia_v)
## sentinel_v_b01 sentinel_v_b02 sentinel_v_b03 sentinel_v_b04 sentinel_v_b05
## 1 868 779 573 834 1511
## 2 933 849 768 998 1533
## 3 920 844 797 997 1506
## 4 873 783 632 899 1685
## 5 870 756 627 866 1446
## 6 871 776 650 900 1552
## sentinel_v_b06 sentinel_v_b07 sentinel_v_b08 sentinel_v_b09 sentinel_v_b10
## 1 1739 1642 1902 1007 487
## 2 1811 1736 1984 1746 997
## 3 1716 1676 1961 1406 792
## 4 2013 1972 2204 1436 640
## 5 1649 1678 1925 1404 736
## 6 1820 1755 1976 1540 802
Valor medio de reflectancia de cada clase para cada banda.
mean_reflectancia_o <-aggregate(reflectancia_o,list(puntos.ref$Leyenda2),mean,na.rm = TRUE)
mean_reflectancia_p <-aggregate(reflectancia_p,list(puntos.ref$Leyenda2),mean,na.rm = TRUE)
mean_reflectancia_v <-aggregate(reflectancia_v,list(puntos.ref$Leyenda2),mean,na.rm = TRUE)
Comprobamos los valores medios obtenidos
head(mean_reflectancia_o)
## Group.1 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03 sentinel_o_b04
## 1 Algarrobos 1088.940 954.56 782.280 1126.100
## 2 Bosque Coniferas 934.764 718.50 520.044 723.516
## 3 Bosques Mixtos 1040.033 842.18 704.480 910.860
## 4 Caducifolios 1348.460 1171.52 1135.100 1327.400
## 5 Castaños 1105.320 954.24 1059.780 1233.260
## 6 Eucalipto 926.980 672.34 475.600 629.520
## sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08 sentinel_o_b09
## 1 2144.880 2429.600 2449.420 2619.320 1576.540
## 2 1354.740 1525.268 1502.848 1632.388 881.260
## 3 1535.053 1722.407 1719.520 1846.220 1255.907
## 4 1725.660 1868.640 1904.240 2057.200 1897.600
## 5 1441.640 1580.820 1616.800 1753.700 2244.360
## 6 1082.500 1208.240 1133.800 1279.340 784.000
## sentinel_o_b10
## 1 945.540
## 2 510.576
## 3 784.160
## 4 1326.120
## 5 1609.960
## 6 439.120
head(mean_reflectancia_p)
## Group.1 sentinel_p_b01 sentinel_p_b02 sentinel_p_b03 sentinel_p_b04
## 1 Algarrobos 975.8400 909.180 760.7400 1117.700
## 2 Bosque Coniferas 886.4920 770.172 622.9200 878.916
## 3 Bosques Mixtos 981.1467 885.000 799.7667 1055.140
## 4 Caducifolios 1205.8600 1141.880 1128.9600 1397.740
## 5 Castaños 1204.5000 1250.700 1431.7000 1684.240
## 6 Eucalipto 883.3600 751.060 582.2600 841.220
## sentinel_p_b05 sentinel_p_b06 sentinel_p_b07 sentinel_p_b08 sentinel_p_b09
## 1 2009.660 2294.940 2295.440 2468.160 1641.420
## 2 1624.152 1846.496 1837.832 1984.228 1317.424
## 3 1733.807 1942.313 1934.740 2088.953 1662.413
## 4 1959.420 2166.840 2220.580 2415.540 2575.320
## 5 2091.260 2273.300 2272.560 2425.560 2654.740
## 6 1549.340 1764.960 1713.400 1912.860 1298.580
## sentinel_p_b10
## 1 1013.800
## 2 797.048
## 3 1072.120
## 4 1857.420
## 5 1930.000
## 6 754.360
head(mean_reflectancia_v)
## Group.1 sentinel_v_b01 sentinel_v_b02 sentinel_v_b03 sentinel_v_b04
## 1 Algarrobos 1039.0600 1027.300 1013.60 1254.080
## 2 Bosque Coniferas 937.7360 892.608 827.66 1068.108
## 3 Bosques Mixtos 995.8467 954.560 944.60 1152.580
## 4 Caducifolios 1187.9400 1202.160 1338.54 1521.960
## 5 Castaños 1017.3800 1037.660 1059.72 1272.800
## 6 Eucalipto 935.0600 859.700 796.78 1014.260
## sentinel_v_b05 sentinel_v_b06 sentinel_v_b07 sentinel_v_b08 sentinel_v_b09
## 1 1921.700 2227.780 2147.780 2464.500 1785.840
## 2 1618.148 1856.284 1796.328 2052.172 1456.292
## 3 1671.693 1897.693 1844.300 2083.993 1688.320
## 4 1965.040 2230.100 2203.120 2536.360 2666.940
## 5 2116.960 2532.440 2481.180 2779.380 1945.900
## 6 1614.720 1869.980 1818.960 2067.880 1440.500
## sentinel_v_b10
## 1 1068.200
## 2 831.292
## 3 1021.873
## 4 1727.560
## 5 1150.180
## 6 793.820
Ponemos los datos de reflectancias registrados en una columna:
mean_reflectance2_o <- gather(mean_reflectancia_o, key="banda", value="reflectance",sentinel_o_b01:sentinel_o_b10)
mean_reflectance2_p <- gather(mean_reflectancia_p, key="banda", value="reflectance",sentinel_p_b01:sentinel_p_b10)
mean_reflectance2_v <- gather(mean_reflectancia_v, key="banda", value="reflectance",sentinel_v_b01:sentinel_v_b10)
Creamos un nuevo campo de tipo numérico con el número de la banda.
mean_reflectance2_o$banda_num=(as.numeric(str_replace(mean_reflectance2_o$banda,"sentinel_o_b","")))
mean_reflectance2_p$banda_num=(as.numeric(str_replace(mean_reflectance2_p$banda,"sentinel_p_b","")))
mean_reflectance2_v$banda_num=(as.numeric(str_replace(mean_reflectance2_v$banda,"sentinel_v_b","")))
Finalmente, visualizamos la firma espectral de cada una de clases:
#Escena Otoño
ggplot(mean_reflectance2_o,aes(x=banda_num,y=reflectance))+
geom_line(aes(colour = Group.1))+theme_bw()
#Escena Primavera
ggplot(mean_reflectance2_p,aes(x=banda_num,y=reflectance))+
geom_line(aes(colour = Group.1))+theme_bw()
#Escena Verano
ggplot(mean_reflectance2_v,aes(x=banda_num,y=reflectance))+
geom_line(aes(colour = Group.1))+theme_bw()
Para esta tarea utilizaremos uno de los operadores clásicos empleados en Teledetección para clasificar imágenes, en este caso un clasificador por el método de Random Forest. Para ello se empleará la función superClass dentro del paquete RStoolbox. De entre los parámetros a incluir en la función destacar que:
trainData contiene el muestreo a emplear en la clasificación.
trainPartition: contiene un valor indicando el tamaño de la muestra destinada al entrenamiento.
model indica el tipo de clasficación que se desea realizar, por defecto la función aplica un random forest (rf), que es el que realizaremos.
#puntos.ref<- as_Spatial(puntos.ref)
puntos.ref@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
R.Forest<- superClass(sentinel_o,
trainData = puntos.ref,
trainPartition =0.5,
responseCol = "Leyenda2",
model = "rf") #Random Forest
El resultado de la clasificación se muestra recogido en una variable de tipo lista. En el quinto elemento de la lista se recoge el resultado cartográfico mediante un rasterLayer, pudiendo ser representado por ejemplo mediante la función plot.
leyenda_colores <- viridis::viridis(13)
plot(R.Forest$map,
col=leyenda_colores,
legend = FALSE)
legend("topright",cex=0.65, y.intersp = 0.55,x.intersp = 0.5,
legend = levels(as.factor(puntos.ref$Leyenda2)),
fill = leyenda_colores ,title = "",
inset=c(0,0))
Además del producto cartográfico es necesario realizar una evaluación de la calidad temática. Para ello mediante en el segundo elemento de la lista, denominado modelFit se encuentra la matriz de confusión resultante así como los valores de exactitud global y kapp obtenidos en el entrenamiento. Por otro lado en el elemento results aparecen recogidos estos elementos de calidad global y su desviación.
R.Forest$modelFit
## [[1]]
## TrainAccuracy TrainKappa method
## 1 0.4030088 0.3079636 rf
##
## [[2]]
## Cross-Validated (5 fold) Confusion Matrix
##
## (entries are average cell counts across resamples)
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 1.0 0.8 0.8 0.2
## Bosque Coniferas 2.2 15.4 4.4 0.0
## Bosques Mixtos 0.6 3.4 3.2 0.0
## Caducifolios 0.0 0.2 0.0 2.0
## Castaños 0.0 0.0 0.0 0.4
## Eucalipto 0.0 0.6 0.4 0.0
## Matorral 0.2 0.0 0.8 0.4
## Pinsapos 0.0 1.0 0.0 0.0
## Quercineas 0.4 1.6 1.6 0.0
## Suelos 0.2 0.4 0.6 0.2
## Veg. Dispersa 0.0 1.6 1.6 1.8
## Veg. Ribera 0.0 0.0 0.6 0.0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0.0 0.0 0.2 0.0 0.2 0.0
## Bosque Coniferas 0.0 1.2 1.4 2.0 1.8 1.8
## Bosques Mixtos 0.0 0.6 1.0 0.4 1.2 0.4
## Caducifolios 0.2 0.0 0.4 0.0 0.0 0.4
## Castaños 3.6 0.0 0.0 0.0 0.0 0.0
## Eucalipto 0.0 1.2 0.0 0.6 0.0 0.2
## Matorral 0.0 0.4 3.6 0.0 0.4 0.4
## Pinsapos 0.0 0.0 0.0 0.8 0.4 0.4
## Quercineas 0.0 0.0 0.0 0.4 5.0 0.0
## Suelos 0.0 0.0 0.6 0.6 0.0 0.2
## Veg. Dispersa 0.4 1.2 2.6 0.0 0.6 1.2
## Veg. Ribera 0.0 0.2 0.2 0.2 0.4 0.0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0.2 0.0
## Bosque Coniferas 1.8 1.8
## Bosques Mixtos 0.8 1.0
## Caducifolios 1.2 0.0
## Castaños 0.0 0.0
## Eucalipto 1.2 0.4
## Matorral 1.2 0.0
## Pinsapos 0.0 0.2
## Quercineas 1.0 0.6
## Suelos 0.8 0.0
## Veg. Dispersa 6.4 0.0
## Veg. Ribera 0.2 0.8
##
## Accuracy (average) : 0.403
R.Forest$model$results
## mtry Accuracy Kappa AccuracySD KappaSD
## 1 2 0.3748477 0.2720520 0.039552915 0.03886664
## 2 6 0.4030088 0.3079636 0.030769833 0.03478246
## 3 10 0.4010868 0.3061705 0.009339911 0.00798516
#puntos.ref<- as_Spatial(puntos.ref)
puntos.ref@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
R.Forest<- superClass(sentinel_p,
trainData = puntos.ref,
trainPartition =0.5,
responseCol = "Leyenda2",
model = "rf") #Random Forest
Representamos el resultado de la clasificación.
leyenda_colores <- viridis::viridis(13)
plot(R.Forest$map,
col=leyenda_colores,
legend = FALSE)
legend("topright",cex=0.65, y.intersp = 0.55,x.intersp = 0.5,
legend = levels(as.factor(puntos.ref$Leyenda2)),
fill = leyenda_colores ,title = "",
inset=c(0,0))
Evaluación de la calidad temática. Matriz y valores de exactitud global y kapp obtenidos en el entrenamiento.
R.Forest$modelFit
## [[1]]
## TrainAccuracy TrainKappa method
## 1 0.3872055 0.2845665 rf
##
## [[2]]
## Cross-Validated (5 fold) Confusion Matrix
##
## (entries are average cell counts across resamples)
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 1.8 1.2 0.2 0.0
## Bosque Coniferas 2.2 14.2 5.6 0.2
## Bosques Mixtos 0.2 3.8 2.8 0.4
## Caducifolios 0.0 0.2 0.0 1.4
## Castaños 0.0 0.0 0.4 0.0
## Eucalipto 0.0 1.0 0.0 0.2
## Matorral 0.0 0.4 1.4 0.8
## Pinsapos 0.0 0.4 0.0 0.2
## Quercineas 0.0 2.2 0.8 0.0
## Suelos 0.2 0.4 0.6 0.0
## Veg. Dispersa 0.0 1.0 2.2 1.8
## Veg. Ribera 0.0 0.2 0.2 0.0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0.0 0.2 0.2 0.0 0.2 0.2
## Bosque Coniferas 0.0 2.2 2.4 2.8 2.4 1.2
## Bosques Mixtos 0.6 1.0 2.4 0.4 0.8 1.0
## Caducifolios 0.0 0.0 0.6 0.2 0.2 0.0
## Castaños 2.8 0.0 0.4 0.0 0.0 0.0
## Eucalipto 0.0 1.6 0.0 0.0 0.0 0.0
## Matorral 0.4 0.0 2.2 0.0 0.2 0.6
## Pinsapos 0.0 0.0 0.0 0.8 0.2 0.0
## Quercineas 0.0 0.0 0.2 0.0 4.6 0.0
## Suelos 0.0 0.0 0.2 0.4 0.0 0.6
## Veg. Dispersa 0.8 0.0 1.4 0.4 1.4 1.4
## Veg. Ribera 0.0 0.0 0.0 0.0 0.0 0.0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0.0 0.6
## Bosque Coniferas 1.0 1.6
## Bosques Mixtos 1.6 0.4
## Caducifolios 1.2 0.0
## Castaños 0.6 0.0
## Eucalipto 0.0 0.2
## Matorral 0.8 0.0
## Pinsapos 0.2 0.0
## Quercineas 0.8 0.6
## Suelos 0.4 0.0
## Veg. Dispersa 8.2 0.4
## Veg. Ribera 0.0 0.6
##
## Accuracy (average) : 0.3873
Calidad global y desviación del modelo:
R.Forest$model$results
## mtry Accuracy Kappa AccuracySD KappaSD
## 1 2 0.3742602 0.2682658 0.03607904 0.04348227
## 2 6 0.3872055 0.2845665 0.03441099 0.04202517
## 3 10 0.3723731 0.2686164 0.02570012 0.02958743
#puntos.ref<- as_Spatial(puntos.ref)
puntos.ref@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
R.Forest<- superClass(sentinel_v,
trainData = puntos.ref,
trainPartition =0.5,
responseCol = "Leyenda2",
model = "rf")
Representamos el resultado de la clasificación.
leyenda_colores <- viridis::viridis(13)
plot(R.Forest$map,
col=leyenda_colores,
legend = FALSE)
legend("topright",cex=0.65, y.intersp = 0.55,x.intersp = 0.5,
legend = levels(as.factor(puntos.ref$Leyenda2)),
fill = leyenda_colores ,title = "",
inset=c(0,0))
Evaluamos la calidad temática.
#Matriz y valores de exactitud global y kapp obtenidos en el entrenamiento.
R.Forest$modelFit
## [[1]]
## TrainAccuracy TrainKappa method
## 1 0.4178729 0.3249749 rf
##
## [[2]]
## Cross-Validated (5 fold) Confusion Matrix
##
## (entries are average cell counts across resamples)
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 0.4 0.0 0.2 0.0
## Bosque Coniferas 1.0 16.2 4.6 0.4
## Bosques Mixtos 0.8 3.2 4.6 0.2
## Caducifolios 0.0 0.0 0.0 2.2
## Castaños 1.2 0.4 0.0 0.2
## Eucalipto 0.4 0.4 0.8 0.2
## Matorral 0.6 1.2 1.8 0.2
## Pinsapos 0.0 0.4 0.2 0.0
## Quercineas 0.2 0.6 1.2 0.4
## Suelos 0.2 0.4 0.2 0.0
## Veg. Dispersa 0.0 1.6 1.0 1.2
## Veg. Ribera 0.0 0.6 0.2 0.0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0.8 0.2 0.4 0.0 0.0 0.0
## Bosque Coniferas 0.4 2.2 1.6 1.6 1.6 0.2
## Bosques Mixtos 0.2 1.4 1.2 0.8 0.8 1.2
## Caducifolios 0.0 0.0 0.2 0.2 0.2 0.0
## Castaños 2.4 0.0 0.0 0.0 0.2 0.0
## Eucalipto 0.0 0.4 0.0 0.2 0.0 0.0
## Matorral 0.0 0.2 4.2 0.2 0.0 0.4
## Pinsapos 0.0 0.0 0.0 0.8 0.2 0.2
## Quercineas 0.0 0.4 0.2 0.6 5.6 0.2
## Suelos 0.0 0.0 0.2 0.0 0.0 0.8
## Veg. Dispersa 0.2 0.0 2.0 0.4 0.8 2.0
## Veg. Ribera 0.4 0.2 0.0 0.2 0.6 0.0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0.2 0.0
## Bosque Coniferas 1.8 0.6
## Bosques Mixtos 1.4 0.8
## Caducifolios 1.4 0.0
## Castaños 0.0 0.0
## Eucalipto 0.0 0.2
## Matorral 1.4 0.4
## Pinsapos 0.0 0.2
## Quercineas 0.6 1.6
## Suelos 1.0 0.0
## Veg. Dispersa 7.2 0.2
## Veg. Ribera 0.0 0.6
##
## Accuracy (average) : 0.418
R.Forest$model$results
## mtry Accuracy Kappa AccuracySD KappaSD
## 1 2 0.4086646 0.3130124 0.06304561 0.07577939
## 2 6 0.4178729 0.3249749 0.05348709 0.06318588
## 3 10 0.4067958 0.3120185 0.05848534 0.06940536
En el paso anterior se generó un dataframe con los valores medios de reflectancia para cada clase. Ahora se va a generar un dataframe que contendrá para cada punto su etiqueta y los valores de reflectancia de todas y cada una de las bandas. Advertir que el objeto train_data@data apunta a toda esa información, de forma que *@* es un operador especial que permite acceder a un objeto dentro de otro objeto. Nota: Se va a crear una variable denominada train_data igual a puntos.ref por si el trascurso de la tarea se comete un error, pudiendo tener así un backup de los datos hasta este punto.
train_data_o = as_Spatial(puntos.ref_backup)
train_data_o@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
train_data_o@data=data.frame(train_data_o@data,reflectancia_o[match(rownames(train_data_o@data),rownames(reflectancia_o)),])
Veamos el resultado obtenido.
str(train_data_o)
## Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
## ..@ data :'data.frame': 1100 obs. of 15 variables:
## .. ..$ OBJECTID : num [1:1100] 1 1 1 1 1 1 1 1 1 1 ...
## .. ..$ NOM_FORARB : chr [1:1100] "Alcornocales" "Alcornocales" "Alcornocales" "Alcornocales" ...
## .. ..$ Shape_Leng : num [1:1100] 34046 34046 34046 34046 34046 ...
## .. ..$ Shape_Area : num [1:1100] 4419619 4419619 4419619 4419619 4419619 ...
## .. ..$ Leyenda2 : Factor w/ 12 levels "Algarrobos","Bosque Coniferas",..: 9 9 9 9 9 9 9 9 9 9 ...
## .. ..$ sentinel_o_b01: num [1:1100] 935 1069 869 875 922 ...
## .. ..$ sentinel_o_b02: num [1:1100] 701 871 562 583 681 696 609 753 500 654 ...
## .. ..$ sentinel_o_b03: num [1:1100] 434 703 356 360 469 471 377 542 282 391 ...
## .. ..$ sentinel_o_b04: num [1:1100] 684 985 456 454 694 702 477 791 254 562 ...
## .. ..$ sentinel_o_b05: num [1:1100] 1405 2058 800 843 1312 ...
## .. ..$ sentinel_o_b06: num [1:1100] 1705 2270 962 853 1720 ...
## .. ..$ sentinel_o_b07: num [1:1100] 1545 2263 787 901 1605 ...
## .. ..$ sentinel_o_b08: num [1:1100] 1754 2531 883 1032 1697 ...
## .. ..$ sentinel_o_b09: num [1:1100] 689 1983 497 755 1248 ...
## .. ..$ sentinel_o_b10: num [1:1100] 340 1174 258 333 698 ...
## ..@ coords.nrs : num(0)
## ..@ coords : num [1:1100, 1:2] 326741 329242 328773 331246 329865 ...
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : NULL
## .. .. ..$ : chr [1:2] "lon" "lat"
## ..@ bbox : num [1:2, 1:2] 312560 4052227 331754 4072825
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : chr [1:2] "lon" "lat"
## .. .. ..$ : chr [1:2] "min" "max"
## ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
## .. .. ..@ projargs: chr "+proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
## .. .. ..$ comment: chr "PROJCRS[\"ETRS89 / UTM zone 30N\",\n BASEGEOGCRS[\"ETRS89\",\n DATUM[\"European Terrestrial Reference"| __truncated__
De entre las variables, diez corresponden a las bandas espectrales, siendo estas últimas nuestras variables predictoras de la variable respuesta consistente en las clases.
Podemos ver un resumen estadístico de la variable:
summary(train_data_o@data)
## OBJECTID NOM_FORARB Shape_Leng Shape_Area
## Min. : 1.0 Length:1100 Min. : 1805 Min. : 52512
## 1st Qu.: 6.0 Class :character 1st Qu.: 3900 1st Qu.: 84213
## Median :11.5 Mode :character Median : 26445 Median : 2351264
## Mean :11.5 Mean : 64448 Mean : 9131237
## 3rd Qu.:17.0 3rd Qu.: 80456 3rd Qu.:10093586
## Max. :22.0 Max. :455519 Max. :81665992
##
## Leyenda2 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## Bosque Coniferas:250 Min. : 761 Min. : 457.0 Min. : 249.0
## Bosques Mixtos :150 1st Qu.: 888 1st Qu.: 632.8 1st Qu.: 408.0
## Veg. Dispersa :150 Median : 980 Median : 787.5 Median : 587.5
## Matorral :100 Mean :1103 Mean : 905.1 Mean : 775.2
## Quercineas :100 3rd Qu.:1126 3rd Qu.: 995.2 3rd Qu.: 963.2
## Algarrobos : 50 Max. :5384 Max. :5290.0 Max. :5925.0
## (Other) :300
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## Min. : 226.0 Min. : 247 Min. : 233 Min. : 212 Min. : 187
## 1st Qu.: 561.5 1st Qu.:1030 1st Qu.:1158 1st Qu.:1146 1st Qu.:1234
## Median : 849.0 Median :1566 Median :1770 Median :1766 Median :1918
## Mean : 979.8 Mean :1561 Mean :1737 Mean :1732 Mean :1869
## 3rd Qu.:1241.5 3rd Qu.:2002 3rd Qu.:2242 3rd Qu.:2275 3rd Qu.:2448
## Max. :6146.0 Max. :6331 Max. :6394 Max. :6354 Max. :6308
##
## sentinel_o_b09 sentinel_o_b10
## Min. : 53.0 Min. : 28.0
## 1st Qu.: 600.5 1st Qu.: 309.2
## Median :1121.0 Median : 639.0
## Mean :1300.0 Mean : 834.0
## 3rd Qu.:1829.5 3rd Qu.:1186.0
## Max. :5973.0 Max. :4484.0
##
En este caso se observa como no hay datos ausentes (NA). En caso de que aparecieran es importante eliminarlos, empleando para ello la función na.omit(). Una vez aplicada podemos emplear la función complete.cases() para comprobar que se han borrado.
train_data_o@data= na.omit(train_data_o@data)
complete.cases(train_data_o@data)
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [15] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [29] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [43] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [57] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [71] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [85] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [99] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [113] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [127] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [141] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [155] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [169] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [183] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [197] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [211] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [225] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [239] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [253] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [267] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [281] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [295] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [309] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [323] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [337] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [351] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [365] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [379] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [393] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [407] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [421] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [435] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [449] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [463] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [477] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [491] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [505] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [519] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [533] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [547] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [561] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [575] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [589] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [603] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [617] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [631] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [645] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [659] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [673] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [687] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [701] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [715] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [729] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [743] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [757] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [771] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [785] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [799] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [813] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [827] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [841] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [855] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [869] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [883] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [897] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [911] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [925] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [939] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [953] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [967] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [981] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [995] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1009] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1023] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1037] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1051] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1065] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1079] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [1093] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
train_data_p = as_Spatial(puntos.ref_backup)
train_data_p@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
train_data_p@data=data.frame(train_data_p@data,reflectancia_p[match(rownames(train_data_p@data),rownames(reflectancia_p)),])
Veamos el resultado obtenido.
str(train_data_p)
## Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
## ..@ data :'data.frame': 1100 obs. of 15 variables:
## .. ..$ OBJECTID : num [1:1100] 1 1 1 1 1 1 1 1 1 1 ...
## .. ..$ NOM_FORARB : chr [1:1100] "Alcornocales" "Alcornocales" "Alcornocales" "Alcornocales" ...
## .. ..$ Shape_Leng : num [1:1100] 34046 34046 34046 34046 34046 ...
## .. ..$ Shape_Area : num [1:1100] 4419619 4419619 4419619 4419619 4419619 ...
## .. ..$ Leyenda2 : Factor w/ 12 levels "Algarrobos","Bosque Coniferas",..: 9 9 9 9 9 9 9 9 9 9 ...
## .. ..$ sentinel_p_b01: num [1:1100] 888 879 797 812 826 832 859 806 778 806 ...
## .. ..$ sentinel_p_b02: num [1:1100] 766 774 657 647 674 703 716 656 596 672 ...
## .. ..$ sentinel_p_b03: num [1:1100] 576 607 452 417 463 497 491 440 380 473 ...
## .. ..$ sentinel_p_b04: num [1:1100] 842 949 674 637 761 767 768 700 595 747 ...
## .. ..$ sentinel_p_b05: num [1:1100] 1607 1903 1560 1653 1453 ...
## .. ..$ sentinel_p_b06: num [1:1100] 1785 2197 1783 1993 1666 ...
## .. ..$ sentinel_p_b07: num [1:1100] 1756 2237 1800 1968 1675 ...
## .. ..$ sentinel_p_b08: num [1:1100] 1922 2383 2040 2119 1839 ...
## .. ..$ sentinel_p_b09: num [1:1100] 1127 1706 1176 1181 1246 ...
## .. ..$ sentinel_p_b10: num [1:1100] 618 955 612 547 643 788 668 608 385 680 ...
## ..@ coords.nrs : num(0)
## ..@ coords : num [1:1100, 1:2] 326741 329242 328773 331246 329865 ...
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : NULL
## .. .. ..$ : chr [1:2] "lon" "lat"
## ..@ bbox : num [1:2, 1:2] 312560 4052227 331754 4072825
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : chr [1:2] "lon" "lat"
## .. .. ..$ : chr [1:2] "min" "max"
## ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
## .. .. ..@ projargs: chr "+proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
## .. .. ..$ comment: chr "PROJCRS[\"ETRS89 / UTM zone 30N\",\n BASEGEOGCRS[\"ETRS89\",\n DATUM[\"European Terrestrial Reference"| __truncated__
Resumen estadístico de la variable.
summary(train_data_p@data)
## OBJECTID NOM_FORARB Shape_Leng Shape_Area
## Min. : 1.0 Length:1100 Min. : 1805 Min. : 52512
## 1st Qu.: 6.0 Class :character 1st Qu.: 3900 1st Qu.: 84213
## Median :11.5 Mode :character Median : 26445 Median : 2351264
## Mean :11.5 Mean : 64448 Mean : 9131237
## 3rd Qu.:17.0 3rd Qu.: 80456 3rd Qu.:10093586
## Max. :22.0 Max. :455519 Max. :81665992
##
## Leyenda2 sentinel_p_b01 sentinel_p_b02 sentinel_p_b03
## Bosque Coniferas:250 Min. : 723.0 Min. : 509.0 Min. : 324.0
## Bosques Mixtos :150 1st Qu.: 845.8 1st Qu.: 711.0 1st Qu.: 522.8
## Veg. Dispersa :150 Median : 928.0 Median : 827.0 Median : 697.5
## Matorral :100 Mean : 996.2 Mean : 907.4 Mean : 816.8
## Quercineas :100 3rd Qu.:1099.0 3rd Qu.:1056.2 3rd Qu.:1026.0
## Algarrobos : 50 Max. :1962.0 Max. :2084.0 Max. :2295.0
## (Other) :300
## sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07 sentinel_p_b08
## Min. : 430.0 Min. : 729 Min. : 761 Min. : 613 Min. : 724
## 1st Qu.: 794.2 1st Qu.:1513 1st Qu.:1722 1st Qu.:1705 1st Qu.:1852
## Median : 980.0 Median :1745 Median :1965 Median :1958 Median :2129
## Mean :1084.9 Mean :1772 Mean :1989 Mean :1993 Mean :2155
## 3rd Qu.:1297.0 3rd Qu.:2000 3rd Qu.:2221 3rd Qu.:2238 3rd Qu.:2412
## Max. :2584.0 Max. :3219 Max. :3571 Max. :3714 Max. :4126
##
## sentinel_p_b09 sentinel_p_b10
## Min. : 494 Min. : 264.0
## 1st Qu.:1216 1st Qu.: 679.8
## Median :1580 Median : 987.5
## Mean :1739 Mean :1145.3
## 3rd Qu.:2160 3rd Qu.:1483.0
## Max. :4883 Max. :3668.0
##
No hay datos ausentes (NA)
train_data_v = as_Spatial(puntos.ref_backup)
train_data_v@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
train_data_v@data=data.frame(train_data_v@data,reflectancia_v[match(rownames(train_data_v@data),rownames(reflectancia_v)),])
Veamos el resultado obtenido.
str(train_data_v)
## Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
## ..@ data :'data.frame': 1100 obs. of 15 variables:
## .. ..$ OBJECTID : num [1:1100] 1 1 1 1 1 1 1 1 1 1 ...
## .. ..$ NOM_FORARB : chr [1:1100] "Alcornocales" "Alcornocales" "Alcornocales" "Alcornocales" ...
## .. ..$ Shape_Leng : num [1:1100] 34046 34046 34046 34046 34046 ...
## .. ..$ Shape_Area : num [1:1100] 4419619 4419619 4419619 4419619 4419619 ...
## .. ..$ Leyenda2 : Factor w/ 12 levels "Algarrobos","Bosque Coniferas",..: 9 9 9 9 9 9 9 9 9 9 ...
## .. ..$ sentinel_v_b01: num [1:1100] 868 933 920 873 870 871 847 900 824 877 ...
## .. ..$ sentinel_v_b02: num [1:1100] 779 849 844 783 756 776 742 819 722 791 ...
## .. ..$ sentinel_v_b03: num [1:1100] 573 768 797 632 627 650 545 700 527 668 ...
## .. ..$ sentinel_v_b04: num [1:1100] 834 998 997 899 866 900 793 970 774 936 ...
## .. ..$ sentinel_v_b05: num [1:1100] 1511 1533 1506 1685 1446 ...
## .. ..$ sentinel_v_b06: num [1:1100] 1739 1811 1716 2013 1649 ...
## .. ..$ sentinel_v_b07: num [1:1100] 1642 1736 1676 1972 1678 ...
## .. ..$ sentinel_v_b08: num [1:1100] 1902 1984 1961 2204 1925 ...
## .. ..$ sentinel_v_b09: num [1:1100] 1007 1746 1406 1436 1404 ...
## .. ..$ sentinel_v_b10: num [1:1100] 487 997 792 640 736 802 530 833 446 602 ...
## ..@ coords.nrs : num(0)
## ..@ coords : num [1:1100, 1:2] 326741 329242 328773 331246 329865 ...
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : NULL
## .. .. ..$ : chr [1:2] "lon" "lat"
## ..@ bbox : num [1:2, 1:2] 312560 4052227 331754 4072825
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : chr [1:2] "lon" "lat"
## .. .. ..$ : chr [1:2] "min" "max"
## ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
## .. .. ..@ projargs: chr "+proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
## .. .. ..$ comment: chr "PROJCRS[\"ETRS89 / UTM zone 30N\",\n BASEGEOGCRS[\"ETRS89\",\n DATUM[\"European Terrestrial Reference"| __truncated__
Resumen estadístico de la variable.
summary(train_data_v@data)
## OBJECTID NOM_FORARB Shape_Leng Shape_Area
## Min. : 1.0 Length:1100 Min. : 1805 Min. : 52512
## 1st Qu.: 6.0 Class :character 1st Qu.: 3900 1st Qu.: 84213
## Median :11.5 Mode :character Median : 26445 Median : 2351264
## Mean :11.5 Mean : 64448 Mean : 9131237
## 3rd Qu.:17.0 3rd Qu.: 80456 3rd Qu.:10093586
## Max. :22.0 Max. :455519 Max. :81665992
##
## Leyenda2 sentinel_v_b01 sentinel_v_b02 sentinel_v_b03
## Bosque Coniferas:250 Min. : 786.0 Min. : 639.0 Min. : 471.0
## Bosques Mixtos :150 1st Qu.: 892.0 1st Qu.: 815.8 1st Qu.: 691.8
## Veg. Dispersa :150 Median : 966.5 Median : 928.0 Median : 883.0
## Matorral :100 Mean :1017.3 Mean : 987.6 Mean : 981.8
## Quercineas :100 3rd Qu.:1088.2 3rd Qu.:1093.0 3rd Qu.:1167.8
## Algarrobos : 50 Max. :1776.0 Max. :1883.0 Max. :2379.0
## (Other) :300
## sentinel_v_b04 sentinel_v_b05 sentinel_v_b06 sentinel_v_b07 sentinel_v_b08
## Min. : 629.0 Min. : 888 Min. :1121 Min. :1036 Min. :1250
## 1st Qu.: 935.8 1st Qu.:1520 1st Qu.:1749 1st Qu.:1690 1st Qu.:1928
## Median :1131.0 Median :1744 Median :2002 Median :1948 Median :2221
## Mean :1199.3 Mean :1758 Mean :2021 Mean :1967 Mean :2244
## 3rd Qu.:1378.0 3rd Qu.:1952 3rd Qu.:2262 3rd Qu.:2214 3rd Qu.:2520
## Max. :2539.0 Max. :2895 Max. :3210 Max. :3156 Max. :3658
##
## sentinel_v_b09 sentinel_v_b10
## Min. : 651 Min. : 320
## 1st Qu.:1302 1st Qu.: 689
## Median :1674 Median : 987
## Mean :1811 Mean :1100
## 3rd Qu.:2170 3rd Qu.:1357
## Max. :4555 Max. :3242
##
No hay datos ausentes (NA).
Es recomendable separar de forma aleatoria el set de entrenamiento inicial en 3 grupos: entrenamiento, validación y testeo. En este caso solo lo vamos a separar en los dos primeros. Para ello, en primer lugar es necesario establecer un valor predefinido de semilla empleando set.seed().
hre_seed<- 123
set.seed(hre_seed)
Ahora, dividiremos nuestro set de entrenamiento inicial en entrenamiento y testeo usando para ello la función createDataPartition() del paquete caret. Por ejemplo, vamos a establecer que el 80% de los datos iniciales pasen a ser de entrenamiento y el 20% de test. Hay que recordar que el entrenamiento nos permitirá optimizar los parámetros iniciales del modelo mientras que los de testeo nos permitirán evaluar la calidad del mismo.
Nota: Se ha establecido como variable train_data_x@data$leyenda pues es esta la que que contiene la etiqueta de las clases. Por otro lado el parámetro p contiene el porcentaje a emplear en la separación de la muestra. Finalmente, el parámetro list indica si devuelve una lista o una matriz, en nuestro caso indicaremos FALSE de forma que devuelve una matriz.
Así, el resultado de la variable inTraining como podemos comprobar es una lista de valores núméricos indicando el índice de los elementos empleados para entrenamiento.
# Escena de Otoño
inTraining_o <- createDataPartition(train_data_o@data$Leyenda2, p=0.80,list=FALSE)
training_o <-train_data_o@data[inTraining_o,]
training_o=training_o[,-(1:4)] #Borramos columnas no necesarias
testing_o <- train_data_o@data[-inTraining_o,]
testing_o=testing_o[,-(1:4)] #Borramos columnas no necesarias
# Escena de Primavera
inTraining_p <- createDataPartition(train_data_p@data$Leyenda2, p=0.80,list=FALSE)
training_p <-train_data_p@data[inTraining_p,]
training_p=training_p[,-(1:4)] #Borramos columnas no necesarias
testing_p <- train_data_p@data[-inTraining_p,]
testing_p=testing_p[,-(1:4)] #Borramos columnas no necesarias
# Escena de Verano
inTraining_v <- createDataPartition(train_data_v@data$Leyenda2, p=0.80,list=FALSE)
training_v <-train_data_v@data[inTraining_v,]
training_v=training_v[,-(1:4)] #Borramos columnas no necesarias
testing_v <- train_data_v@data[-inTraining_v,]
testing_v=testing_v[,-(1:4)] #Borramos columnas no necesarias
Antes de comenzar el entrenamiento del clasificador de machine learning previo a la clasificación es necesario realizar un chequeo de los set de datos pues puede ser que las imágenes presenten problemas o que hayamos cometido errores en la identificación. Así, en primer lugar vamos a obtener un resumen estadístico de ambos set.
summary(training_o)
## Leyenda2 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## Bosque Coniferas:200 Min. : 761.0 Min. : 457.0 Min. : 249.0
## Bosques Mixtos :120 1st Qu.: 883.0 1st Qu.: 626.8 1st Qu.: 402.8
## Veg. Dispersa :120 Median : 976.5 Median : 781.0 Median : 584.5
## Matorral : 80 Mean :1103.7 Mean : 902.4 Mean : 769.8
## Quercineas : 80 3rd Qu.:1126.0 3rd Qu.: 994.0 3rd Qu.: 955.5
## Algarrobos : 40 Max. :5384.0 Max. :5290.0 Max. :5925.0
## (Other) :240
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## Min. : 226.0 Min. : 247 Min. : 244 Min. : 214 Min. : 187
## 1st Qu.: 551.2 1st Qu.:1015 1st Qu.:1129 1st Qu.:1118 1st Qu.:1187
## Median : 845.5 Median :1540 Median :1721 Median :1742 Median :1896
## Mean : 970.3 Mean :1542 Mean :1714 Mean :1705 Mean :1842
## 3rd Qu.:1230.5 3rd Qu.:1984 3rd Qu.:2223 3rd Qu.:2246 3rd Qu.:2416
## Max. :6146.0 Max. :6331 Max. :6394 Max. :6354 Max. :6308
##
## sentinel_o_b09 sentinel_o_b10
## Min. : 59.0 Min. : 29.0
## 1st Qu.: 573.5 1st Qu.: 300.0
## Median :1113.5 Median : 632.5
## Mean :1259.2 Mean : 804.5
## 3rd Qu.:1799.2 3rd Qu.:1153.0
## Max. :5103.0 Max. :3795.0
##
summary(training_p)
## Leyenda2 sentinel_p_b01 sentinel_p_b02 sentinel_p_b03
## Bosque Coniferas:200 Min. : 723.0 Min. : 515.0 Min. : 329.0
## Bosques Mixtos :120 1st Qu.: 849.0 1st Qu.: 713.8 1st Qu.: 532.0
## Veg. Dispersa :120 Median : 932.0 Median : 830.5 Median : 701.0
## Matorral : 80 Mean : 998.1 Mean : 909.7 Mean : 821.4
## Quercineas : 80 3rd Qu.:1099.0 3rd Qu.:1061.2 3rd Qu.:1034.2
## Algarrobos : 40 Max. :1962.0 Max. :2084.0 Max. :2295.0
## (Other) :240
## sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07 sentinel_p_b08
## Min. : 430.0 Min. : 729 Min. : 761 Min. : 834 Min. : 766
## 1st Qu.: 803.5 1st Qu.:1515 1st Qu.:1723 1st Qu.:1706 1st Qu.:1854
## Median : 985.5 Median :1746 Median :1965 Median :1961 Median :2126
## Mean :1089.1 Mean :1772 Mean :1989 Mean :1993 Mean :2154
## 3rd Qu.:1300.0 3rd Qu.:2003 3rd Qu.:2224 3rd Qu.:2238 3rd Qu.:2413
## Max. :2584.0 Max. :3185 Max. :3513 Max. :3614 Max. :3872
##
## sentinel_p_b09 sentinel_p_b10
## Min. : 521 Min. : 277.0
## 1st Qu.:1225 1st Qu.: 693.0
## Median :1592 Median : 991.5
## Mean :1742 Mean :1147.6
## 3rd Qu.:2166 3rd Qu.:1482.0
## Max. :4352 Max. :3301.0
##
summary(training_v)
## Leyenda2 sentinel_v_b01 sentinel_v_b02 sentinel_v_b03
## Bosque Coniferas:200 Min. : 786 Min. : 639.0 Min. : 482.0
## Bosques Mixtos :120 1st Qu.: 891 1st Qu.: 814.0 1st Qu.: 689.8
## Veg. Dispersa :120 Median : 965 Median : 922.5 Median : 878.0
## Matorral : 80 Mean :1014 Mean : 983.5 Mean : 976.4
## Quercineas : 80 3rd Qu.:1082 3rd Qu.:1085.0 3rd Qu.:1163.0
## Algarrobos : 40 Max. :1776 Max. :1883.0 Max. :2379.0
## (Other) :240
## sentinel_v_b04 sentinel_v_b05 sentinel_v_b06 sentinel_v_b07 sentinel_v_b08
## Min. : 629 Min. :1095 Min. :1244 Min. :1114 Min. :1347
## 1st Qu.: 932 1st Qu.:1520 1st Qu.:1745 1st Qu.:1685 1st Qu.:1928
## Median :1128 Median :1742 Median :2000 Median :1942 Median :2220
## Mean :1195 Mean :1756 Mean :2018 Mean :1964 Mean :2242
## 3rd Qu.:1364 3rd Qu.:1949 3rd Qu.:2262 3rd Qu.:2214 3rd Qu.:2510
## Max. :2539 Max. :2895 Max. :3210 Max. :3156 Max. :3658
##
## sentinel_v_b09 sentinel_v_b10
## Min. : 651 Min. : 320.0
## 1st Qu.:1295 1st Qu.: 686.8
## Median :1661 Median : 970.5
## Mean :1803 Mean :1091.1
## 3rd Qu.:2165 3rd Qu.:1331.8
## Max. :4555 Max. :3242.0
##
summary(testing_o)
## Leyenda2 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## Bosque Coniferas:50 Min. : 781.0 Min. : 470.0 Min. : 257.0
## Bosques Mixtos :30 1st Qu.: 898.8 1st Qu.: 658.5 1st Qu.: 430.5
## Veg. Dispersa :30 Median : 995.0 Median : 802.0 Median : 608.0
## Matorral :20 Mean :1098.6 Mean : 915.9 Mean : 797.1
## Quercineas :20 3rd Qu.:1126.0 3rd Qu.: 999.0 3rd Qu.: 990.0
## Algarrobos :10 Max. :2828.0 Max. :2594.0 Max. :2623.0
## (Other) :60
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## Min. : 230 Min. : 278 Min. : 233 Min. : 212 Min. : 197
## 1st Qu.: 610 1st Qu.:1175 1st Qu.:1330 1st Qu.:1270 1st Qu.:1355
## Median : 876 Median :1646 Median :1852 Median :1858 Median :1983
## Mean :1018 Mean :1638 Mean :1827 Mean :1839 Mean :1978
## 3rd Qu.:1273 3rd Qu.:2054 3rd Qu.:2351 3rd Qu.:2402 3rd Qu.:2568
## Max. :2985 Max. :3614 Max. :3895 Max. :4144 Max. :4573
##
## sentinel_o_b09 sentinel_o_b10
## Min. : 53 Min. : 28.0
## 1st Qu.: 727 1st Qu.: 370.8
## Median :1156 Median : 667.5
## Mean :1463 Mean : 952.2
## 3rd Qu.:2166 3rd Qu.:1397.0
## Max. :5973 Max. :4484.0
##
summary(testing_p)
## Leyenda2 sentinel_p_b01 sentinel_p_b02 sentinel_p_b03
## Bosque Coniferas:50 Min. : 725.0 Min. : 509.0 Min. : 324.0
## Bosques Mixtos :30 1st Qu.: 835.0 1st Qu.: 698.8 1st Qu.: 495.8
## Veg. Dispersa :30 Median : 921.5 Median : 813.0 Median : 658.0
## Matorral :20 Mean : 989.0 Mean : 898.3 Mean : 798.6
## Quercineas :20 3rd Qu.:1099.8 3rd Qu.:1048.2 3rd Qu.:1005.5
## Algarrobos :10 Max. :1822.0 Max. :1966.0 Max. :2261.0
## (Other) :60
## sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07 sentinel_p_b08
## Min. : 436.0 Min. : 757 Min. : 888 Min. : 613 Min. : 724
## 1st Qu.: 766.2 1st Qu.:1506 1st Qu.:1706 1st Qu.:1687 1st Qu.:1846
## Median : 955.0 Median :1734 Median :1969 Median :1950 Median :2134
## Mean :1068.0 Mean :1771 Mean :1988 Mean :1992 Mean :2160
## 3rd Qu.:1280.2 3rd Qu.:1971 3rd Qu.:2209 3rd Qu.:2239 3rd Qu.:2404
## Max. :2539.0 Max. :3219 Max. :3571 Max. :3714 Max. :4126
##
## sentinel_p_b09 sentinel_p_b10
## Min. : 494 Min. : 264.0
## 1st Qu.:1142 1st Qu.: 625.8
## Median :1528 Median : 937.5
## Mean :1731 Mean :1136.2
## 3rd Qu.:2134 3rd Qu.:1494.8
## Max. :4883 Max. :3668.0
##
summary(testing_v)
## Leyenda2 sentinel_v_b01 sentinel_v_b02 sentinel_v_b03
## Bosque Coniferas:50 Min. : 797.0 Min. : 660.0 Min. : 471.0
## Bosques Mixtos :30 1st Qu.: 896.0 1st Qu.: 823.8 1st Qu.: 704.5
## Veg. Dispersa :30 Median : 978.5 Median : 944.0 Median : 918.5
## Matorral :20 Mean :1030.7 Mean :1003.7 Mean :1003.1
## Quercineas :20 3rd Qu.:1119.0 3rd Qu.:1135.0 3rd Qu.:1211.8
## Algarrobos :10 Max. :1625.0 Max. :1749.0 Max. :2198.0
## (Other) :60
## sentinel_v_b04 sentinel_v_b05 sentinel_v_b06 sentinel_v_b07 sentinel_v_b08
## Min. : 645 Min. : 888 Min. :1121 Min. :1036 Min. :1250
## 1st Qu.: 950 1st Qu.:1528 1st Qu.:1783 1st Qu.:1726 1st Qu.:1932
## Median :1153 Median :1758 Median :2020 Median :1974 Median :2236
## Mean :1218 Mean :1766 Mean :2032 Mean :1975 Mean :2252
## 3rd Qu.:1440 3rd Qu.:1972 3rd Qu.:2261 3rd Qu.:2216 3rd Qu.:2536
## Max. :2387 Max. :2655 Max. :2911 Max. :2907 Max. :3319
##
## sentinel_v_b09 sentinel_v_b10
## Min. : 786 Min. : 385.0
## 1st Qu.:1343 1st Qu.: 712.5
## Median :1753 Median :1045.5
## Mean :1843 Mean :1135.2
## 3rd Qu.:2230 3rd Qu.:1447.2
## Max. :4057 Max. :2886.0
##
Posteriormente vamos a generar un grafico de densidades para cada clase / banda que permita representar la distribución de los datos. Esto va a permitirnos evaluar si hay una adecuada separabilidad entre las clases. Además permite determinar si el efecto cizalla en la distribución es acusado o no. Nota: Se han seleccionado los índices 2 al 11 pues en el caso de este ejemplo contienen los datos de reflectancia para cada punto en todas las bandas empleadas.
#Escena de Otoño
featurePlot(x=training_o[,2:11],
y=training_o$Leyenda2,
plot="density",
labels=c("Reflectancia","Distribucion densidades"),
layout=c(2,2))
#Escena de Primavera
featurePlot(x=training_p[,2:11],
y=training_p$Leyenda2,
plot="density",
labels=c("Reflectancia","Distribucion densidades"),
layout=c(2,2))
#Escena de Verano
featurePlot(x=training_v[,2:11],
y=training_v$Leyenda2,
plot="density",
labels=c("Reflectancia","Distribucion densidades"),
layout=c(2,2))
Por otro lado podemos calcular la cizalla mediante la función skewness() de la librería e1071. Nos aportará información sobre si la distribución es simétrica o no. Por lo general, una distribución es simétrica cuando el valor de skewness es 0 o próximo a 0.
#Otoño
skwenessvalues_o <- apply(training_o[,2:11],2,skewness)
skwenessvalues_o
## sentinel_o_b01 sentinel_o_b02 sentinel_o_b03 sentinel_o_b04 sentinel_o_b05
## 4.8662829 4.1051162 3.5583089 2.8626734 1.1915328
## sentinel_o_b06 sentinel_o_b07 sentinel_o_b08 sentinel_o_b09 sentinel_o_b10
## 0.7588326 0.6919157 0.4820169 0.8648015 1.1799476
#Primavera
skwenessvalues_p <- apply(training_p[,2:11],2,skewness)
skwenessvalues_p
## sentinel_p_b01 sentinel_p_b02 sentinel_p_b03 sentinel_p_b04 sentinel_p_b05
## 1.3007667 1.0962697 1.0254771 0.8825870 0.4482581
## sentinel_p_b06 sentinel_p_b07 sentinel_p_b08 sentinel_p_b09 sentinel_p_b10
## 0.3709954 0.4188772 0.4232755 0.7784409 0.9199988
#Verano
skwenessvalues_v <- apply(training_v[,2:11],2,skewness)
skwenessvalues_v
## sentinel_v_b01 sentinel_v_b02 sentinel_v_b03 sentinel_v_b04 sentinel_v_b05
## 1.4014945 1.2149617 1.0941023 1.0514417 0.4358053
## sentinel_v_b06 sentinel_v_b07 sentinel_v_b08 sentinel_v_b09 sentinel_v_b10
## 0.3480263 0.3420557 0.3744854 0.9930445 1.0998042
Por otro lado, si se detecta alguna distribución bimodal puede ser indicativo de una posible presencia de errores groseros en el muestreo. De forma complementaria podemos representar los datos mediante cajas de bigotes con objeto de ver esta presencia.
#Otoño
featurePlot(x=training_o[,2:11],
y=training_o$Leyenda2,
plot="box",
layout=c(2,2))
#Primavera
featurePlot(x=training_p[,2:11],
y=training_p$Leyenda2,
plot="box",
layout=c(2,2))
#Verano
featurePlot(x=training_v[,2:11],
y=training_v$Leyenda2,
plot="box",
layout=c(2,2))
La posible presencia de errores groseros podría deberse por una parte a fallos humanos o tambien a la propia variabilidad del territorio y el comportamiento de las clases. Supongamos por ejemplo que contamos con las clases “uso agricola” y “suelo desnudo”, es posible que estas dos clases presenten un comportamiento similar, siendo adecuado analizar la correlación entre bandas.
A modo de ejemplo se presentan graficos de correlación entre dos clases y 6 bandas espectrales, viendo una clara correlación entre bandas.
band1_2 <-ggplot(data=training_o,aes(sentinel_o_b01,sentinel_o_b02))+
geom_point(aes(shape=Leyenda2,colour=Leyenda2))
band1_3 <-ggplot(data=training_o,aes(sentinel_o_b01,sentinel_o_b03))+
geom_point(aes(shape=Leyenda2,colour=Leyenda2))
band1_4 <-ggplot(data=training_o,aes(sentinel_o_b01,sentinel_o_b04))+
geom_point(aes(shape=Leyenda2,colour=Leyenda2))
band1_5 <-ggplot(data=training_o,aes(sentinel_o_b01,sentinel_o_b05))+
geom_point(aes(shape=Leyenda2,colour=Leyenda2))
grid.arrange(band1_2,band1_3,band1_4,band1_5)
## Warning: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 12. Consider
## specifying shapes manually if you must have them.
## Warning: Removed 400 rows containing missing values (geom_point).
## Warning: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 12. Consider
## specifying shapes manually if you must have them.
## Warning: Removed 400 rows containing missing values (geom_point).
## Warning: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 12. Consider
## specifying shapes manually if you must have them.
## Warning: Removed 400 rows containing missing values (geom_point).
## Warning: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 12. Consider
## specifying shapes manually if you must have them.
## Warning: Removed 400 rows containing missing values (geom_point).
Numéricamente, mediante la función cor() calculamos la correlacion entre las bandas espectrales de la escena. El resultado puede ser “complejo” de analizar, siendo mejor una representación gráfica.
bandcorrelaciones = cor(training_o[,2:11])
Esta sería la representación gráfica de la matriz de correlación
corrplot(bandcorrelaciones,method="number")
corrplot(bandcorrelaciones,method="number",type = "upper")
corrplot(bandcorrelaciones,method="color",type="lower")
Este paso es uno de los mas importantes, pues de la correcta configuración de los parámetros dependerán nuestros resultados. Para ello, usaremos la función trainControl() dentro del paquete caret. Esta se va a encargar de definir la configuración óptima del modelo. La función presenta tres parámetros:
method: “boot”, “boot632”, “optimism_boot”, “boot_all”, “cv”, “repeatedcv”, “LOOCV”,etc…
number: establece el numero de partes o bloques a dividir el conjunto de datos del mismo tamaño.
repeat: número de repeticiones.
La función selecciona el valor que da el mejor resultado.
fitControl <- trainControl(method = "repeatedcv",
number=5,
repeats=5)
El clasificador RF es un método de aprendizaje automático de conjunto, que utiliza el muestreo bootstrap para construir muchos modelos de árboles de decisión individuales.
Usa un subconjunto aleatorio de variables predictoras (por ejemplo, las bandas Sentinel) para dividir los datos de observación en subconjuntos homogéneos, que se utilizan para construir cada modelo de árbol de decisión y una predicción. Luego, se promedian las predicciones del modelo de árbol de decisión individual para producir el etiquetado final.
El clasificador RF se ha utilizado con éxito para la clasificación de imágenes de teledetección porque presentan estas ventajas:
Permiten manejar grandes cantidades de datos.
Están libres de supuestos de distribución normal.
Son robustos a los valores atípicos y al ruido
Sin embargo, como inconventientes:
No es fácil interpretar los resultados del modelo RF.
Esta sesgado a favor de las variables predictoras con muchos niveles de categorías diferentes.
rf_model_o<-train(Leyenda2~.,data=training_o, method="rf",
trControl=fitControl,
prox=TRUE,
fitBest = FALSE,
returnData = TRUE)
print(rf_model_o)
## Random Forest
##
## 880 samples
## 10 predictor
## 12 classes: 'Algarrobos', 'Bosque Coniferas', 'Bosques Mixtos', 'Caducifolios', 'Castaños', 'Eucalipto', 'Matorral', 'Pinsapos', 'Quercineas', 'Suelos', 'Veg. Dispersa', 'Veg. Ribera'
##
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 5 times)
## Summary of sample sizes: 704, 704, 704, 704, 704, 704, ...
## Resampling results across tuning parameters:
##
## mtry Accuracy Kappa
## 2 0.4445455 0.3559707
## 6 0.4597727 0.3755438
## 10 0.4615909 0.3781206
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 10.
plot(rf_model_o)
rf_model_o$finalModel
##
## Call:
## randomForest(x = x, y = y, mtry = min(param$mtry, ncol(x)), proximity = TRUE, fitBest = FALSE, returnData = TRUE)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 10
##
## OOB estimate of error rate: 52.95%
## Confusion matrix:
## Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 20 12 2 0
## Bosque Coniferas 4 128 25 5
## Bosques Mixtos 5 29 54 2
## Caducifolios 0 3 3 15
## Castaños 0 0 1 0
## Eucalipto 0 11 4 0
## Matorral 4 12 8 2
## Pinsapos 0 21 1 0
## Quercineas 1 22 8 0
## Suelos 1 11 4 3
## Veg. Dispersa 1 13 8 8
## Veg. Ribera 0 6 7 0
## Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 0 3 0 1 0
## Bosque Coniferas 0 4 2 7 7 3
## Bosques Mixtos 2 0 2 2 13 0
## Caducifolios 1 2 3 0 0 0
## Castaños 36 0 0 0 0 0
## Eucalipto 0 18 0 0 1 0
## Matorral 0 1 29 0 0 2
## Pinsapos 0 1 0 13 2 1
## Quercineas 0 1 1 0 35 0
## Suelos 0 1 5 2 0 2
## Veg. Dispersa 3 4 14 1 11 6
## Veg. Ribera 0 0 3 0 4 0
## Veg. Dispersa Veg. Ribera class.error
## Algarrobos 2 0 0.5000000
## Bosque Coniferas 13 2 0.3600000
## Bosques Mixtos 9 2 0.5500000
## Caducifolios 12 1 0.6250000
## Castaños 3 0 0.1000000
## Eucalipto 2 4 0.5500000
## Matorral 20 2 0.6375000
## Pinsapos 1 0 0.6750000
## Quercineas 9 3 0.5625000
## Suelos 11 0 0.9500000
## Veg. Dispersa 50 1 0.5833333
## Veg. Ribera 6 14 0.6500000
rf_varImp_o <- varImp(rf_model_o, compete = FALSE)
plot(rf_varImp_o)
Realizaremos un control de calidad.
pred_rf_o <- predict(rf_model_o$finalModel,
newdata = testing_o)
confusionMatrix(data = pred_rf_o, testing_o$Leyenda2)
## Confusion Matrix and Statistics
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 2 1 0 0
## Bosque Coniferas 7 34 8 0
## Bosques Mixtos 1 4 12 1
## Caducifolios 0 0 0 3
## Castaños 0 0 0 0
## Eucalipto 0 0 0 0
## Matorral 0 3 4 2
## Pinsapos 0 0 0 1
## Quercineas 0 4 2 0
## Suelos 0 0 0 1
## Veg. Dispersa 0 3 4 2
## Veg. Ribera 0 1 0 0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 0 0 0 1 0
## Bosque Coniferas 0 6 2 6 5 1
## Bosques Mixtos 0 1 1 1 1 3
## Caducifolios 1 0 0 0 0 1
## Castaños 9 0 0 0 0 0
## Eucalipto 0 0 0 0 0 0
## Matorral 0 1 8 0 1 2
## Pinsapos 0 0 0 2 0 0
## Quercineas 0 0 1 0 10 0
## Suelos 0 0 0 1 0 1
## Veg. Dispersa 0 1 8 0 2 2
## Veg. Ribera 0 1 0 0 0 0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0 0
## Bosque Coniferas 3 3
## Bosques Mixtos 5 2
## Caducifolios 1 0
## Castaños 0 0
## Eucalipto 0 0
## Matorral 7 0
## Pinsapos 0 0
## Quercineas 1 2
## Suelos 0 0
## Veg. Dispersa 13 0
## Veg. Ribera 0 3
##
## Overall Statistics
##
## Accuracy : 0.4409
## 95% CI : (0.3742, 0.5092)
## No Information Rate : 0.2273
## P-Value [Acc > NIR] : 1.999e-12
##
## Kappa : 0.3461
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: Algarrobos Class: Bosque Coniferas
## Sensitivity 0.200000 0.6800
## Specificity 0.990476 0.7588
## Pos Pred Value 0.500000 0.4533
## Neg Pred Value 0.962963 0.8897
## Prevalence 0.045455 0.2273
## Detection Rate 0.009091 0.1545
## Detection Prevalence 0.018182 0.3409
## Balanced Accuracy 0.595238 0.7194
## Class: Bosques Mixtos Class: Caducifolios Class: Castaños
## Sensitivity 0.40000 0.30000 0.90000
## Specificity 0.89474 0.98571 1.00000
## Pos Pred Value 0.37500 0.50000 1.00000
## Neg Pred Value 0.90426 0.96729 0.99526
## Prevalence 0.13636 0.04545 0.04545
## Detection Rate 0.05455 0.01364 0.04091
## Detection Prevalence 0.14545 0.02727 0.04091
## Balanced Accuracy 0.64737 0.64286 0.95000
## Class: Eucalipto Class: Matorral Class: Pinsapos
## Sensitivity 0.00000 0.40000 0.200000
## Specificity 1.00000 0.90000 0.995238
## Pos Pred Value NaN 0.28571 0.666667
## Neg Pred Value 0.95455 0.93750 0.963134
## Prevalence 0.04545 0.09091 0.045455
## Detection Rate 0.00000 0.03636 0.009091
## Detection Prevalence 0.00000 0.12727 0.013636
## Balanced Accuracy 0.50000 0.65000 0.597619
## Class: Quercineas Class: Suelos Class: Veg. Dispersa
## Sensitivity 0.50000 0.100000 0.43333
## Specificity 0.95000 0.990476 0.88421
## Pos Pred Value 0.50000 0.333333 0.37143
## Neg Pred Value 0.95000 0.958525 0.90811
## Prevalence 0.09091 0.045455 0.13636
## Detection Rate 0.04545 0.004545 0.05909
## Detection Prevalence 0.09091 0.013636 0.15909
## Balanced Accuracy 0.72500 0.545238 0.65877
## Class: Veg. Ribera
## Sensitivity 0.30000
## Specificity 0.99048
## Pos Pred Value 0.60000
## Neg Pred Value 0.96744
## Prevalence 0.04545
## Detection Rate 0.01364
## Detection Prevalence 0.02273
## Balanced Accuracy 0.64524
rf_model_p<-train(Leyenda2~.,data=training_p, method="rf",
trControl=fitControl,
prox=TRUE,
fitBest = FALSE,
returnData = TRUE)
print(rf_model_p)
## Random Forest
##
## 880 samples
## 10 predictor
## 12 classes: 'Algarrobos', 'Bosque Coniferas', 'Bosques Mixtos', 'Caducifolios', 'Castaños', 'Eucalipto', 'Matorral', 'Pinsapos', 'Quercineas', 'Suelos', 'Veg. Dispersa', 'Veg. Ribera'
##
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 5 times)
## Summary of sample sizes: 704, 704, 704, 704, 704, 704, ...
## Resampling results across tuning parameters:
##
## mtry Accuracy Kappa
## 2 0.4368182 0.3426578
## 6 0.4454545 0.3544862
## 10 0.4488636 0.3592832
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 10.
plot(rf_model_p)
rf_model_p$finalModel
##
## Call:
## randomForest(x = x, y = y, mtry = min(param$mtry, ncol(x)), proximity = TRUE, fitBest = FALSE, returnData = TRUE)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 10
##
## OOB estimate of error rate: 54.55%
## Confusion matrix:
## Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 16 10 5 0
## Bosque Coniferas 8 131 21 3
## Bosques Mixtos 3 33 48 2
## Caducifolios 0 1 4 11
## Castaños 1 0 2 0
## Eucalipto 1 20 5 0
## Matorral 3 21 10 2
## Pinsapos 0 19 4 0
## Quercineas 1 18 6 0
## Suelos 2 8 11 1
## Veg. Dispersa 0 17 14 7
## Veg. Ribera 4 9 2 0
## Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 0 4 0 1 2
## Bosque Coniferas 0 4 4 4 11 2
## Bosques Mixtos 1 2 8 0 5 6
## Caducifolios 1 1 4 1 2 0
## Castaños 29 0 1 0 0 1
## Eucalipto 0 11 0 0 1 0
## Matorral 2 1 26 1 3 3
## Pinsapos 0 1 1 9 1 2
## Quercineas 0 1 1 0 37 0
## Suelos 0 0 4 2 0 6
## Veg. Dispersa 4 1 6 1 7 2
## Veg. Ribera 0 0 0 0 5 0
## Veg. Dispersa Veg. Ribera class.error
## Algarrobos 1 1 0.6000000
## Bosque Coniferas 10 2 0.3450000
## Bosques Mixtos 12 0 0.6000000
## Caducifolios 15 0 0.7250000
## Castaños 6 0 0.2750000
## Eucalipto 1 1 0.7250000
## Matorral 8 0 0.6750000
## Pinsapos 3 0 0.7750000
## Quercineas 14 2 0.5375000
## Suelos 6 0 0.8500000
## Veg. Dispersa 61 0 0.4916667
## Veg. Ribera 5 15 0.6250000
rf_varImp_p <- varImp(rf_model_p, compete = FALSE)
plot(rf_varImp_p)
Control de calidad:
pred_rf_p <- predict(rf_model_p$finalModel,
newdata = testing_p)
confusionMatrix(data = pred_rf_p, testing_p$Leyenda2)
## Confusion Matrix and Statistics
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 5 2 0 0
## Bosque Coniferas 1 32 12 1
## Bosques Mixtos 0 8 9 1
## Caducifolios 0 0 0 1
## Castaños 0 0 0 0
## Eucalipto 0 0 1 0
## Matorral 0 2 1 1
## Pinsapos 0 1 1 1
## Quercineas 0 2 5 0
## Suelos 3 1 1 0
## Veg. Dispersa 0 1 0 5
## Veg. Ribera 1 1 0 0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 1 0 0 0 0
## Bosque Coniferas 0 4 6 4 4 1
## Bosques Mixtos 0 1 4 1 1 3
## Caducifolios 0 0 1 1 0 0
## Castaños 7 0 0 0 0 0
## Eucalipto 0 3 0 0 0 0
## Matorral 1 0 5 0 0 1
## Pinsapos 0 0 0 2 0 0
## Quercineas 0 0 0 0 12 0
## Suelos 0 0 0 0 0 1
## Veg. Dispersa 2 0 3 1 3 4
## Veg. Ribera 0 1 1 1 0 0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0 0
## Bosque Coniferas 3 2
## Bosques Mixtos 2 1
## Caducifolios 4 0
## Castaños 1 0
## Eucalipto 0 1
## Matorral 0 0
## Pinsapos 1 0
## Quercineas 2 2
## Suelos 2 0
## Veg. Dispersa 15 1
## Veg. Ribera 0 3
##
## Overall Statistics
##
## Accuracy : 0.4318
## 95% CI : (0.3654, 0.5001)
## No Information Rate : 0.2273
## P-Value [Acc > NIR] : 1.419e-11
##
## Kappa : 0.3412
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: Algarrobos Class: Bosque Coniferas
## Sensitivity 0.50000 0.6400
## Specificity 0.98571 0.7765
## Pos Pred Value 0.62500 0.4571
## Neg Pred Value 0.97642 0.8800
## Prevalence 0.04545 0.2273
## Detection Rate 0.02273 0.1455
## Detection Prevalence 0.03636 0.3182
## Balanced Accuracy 0.74286 0.7082
## Class: Bosques Mixtos Class: Caducifolios Class: Castaños
## Sensitivity 0.30000 0.100000 0.70000
## Specificity 0.88421 0.971429 0.99524
## Pos Pred Value 0.29032 0.142857 0.87500
## Neg Pred Value 0.88889 0.957746 0.98585
## Prevalence 0.13636 0.045455 0.04545
## Detection Rate 0.04091 0.004545 0.03182
## Detection Prevalence 0.14091 0.031818 0.03636
## Balanced Accuracy 0.59211 0.535714 0.84762
## Class: Eucalipto Class: Matorral Class: Pinsapos
## Sensitivity 0.30000 0.25000 0.200000
## Specificity 0.99048 0.97000 0.980952
## Pos Pred Value 0.60000 0.45455 0.333333
## Neg Pred Value 0.96744 0.92823 0.962617
## Prevalence 0.04545 0.09091 0.045455
## Detection Rate 0.01364 0.02273 0.009091
## Detection Prevalence 0.02273 0.05000 0.027273
## Balanced Accuracy 0.64524 0.61000 0.590476
## Class: Quercineas Class: Suelos Class: Veg. Dispersa
## Sensitivity 0.60000 0.100000 0.50000
## Specificity 0.94500 0.966667 0.89474
## Pos Pred Value 0.52174 0.125000 0.42857
## Neg Pred Value 0.95939 0.957547 0.91892
## Prevalence 0.09091 0.045455 0.13636
## Detection Rate 0.05455 0.004545 0.06818
## Detection Prevalence 0.10455 0.036364 0.15909
## Balanced Accuracy 0.77250 0.533333 0.69737
## Class: Veg. Ribera
## Sensitivity 0.30000
## Specificity 0.97619
## Pos Pred Value 0.37500
## Neg Pred Value 0.96698
## Prevalence 0.04545
## Detection Rate 0.01364
## Detection Prevalence 0.03636
## Balanced Accuracy 0.63810
rf_model_v<-train(Leyenda2~.,data=training_v, method="rf",
trControl=fitControl,
prox=TRUE,
fitBest = FALSE,
returnData = TRUE)
print(rf_model_v)
## Random Forest
##
## 880 samples
## 10 predictor
## 12 classes: 'Algarrobos', 'Bosque Coniferas', 'Bosques Mixtos', 'Caducifolios', 'Castaños', 'Eucalipto', 'Matorral', 'Pinsapos', 'Quercineas', 'Suelos', 'Veg. Dispersa', 'Veg. Ribera'
##
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 5 times)
## Summary of sample sizes: 704, 704, 704, 704, 704, 704, ...
## Resampling results across tuning parameters:
##
## mtry Accuracy Kappa
## 2 0.4375000 0.3471103
## 6 0.4415909 0.3535509
## 10 0.4456818 0.3585097
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 10.
plot(rf_model_v)
rf_model_v$finalModel
##
## Call:
## randomForest(x = x, y = y, mtry = min(param$mtry, ncol(x)), proximity = TRUE, fitBest = FALSE, returnData = TRUE)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 10
##
## OOB estimate of error rate: 53.98%
## Confusion matrix:
## Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 12 12 5 0
## Bosque Coniferas 2 127 23 3
## Bosques Mixtos 0 29 57 0
## Caducifolios 0 2 2 10
## Castaños 3 2 1 0
## Eucalipto 1 17 7 0
## Matorral 2 12 14 0
## Pinsapos 0 14 5 0
## Quercineas 1 10 5 1
## Suelos 0 7 5 2
## Veg. Dispersa 0 17 5 11
## Veg. Ribera 0 5 3 0
## Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 6 2 2 0 0 1
## Bosque Coniferas 4 5 8 7 7 1
## Bosques Mixtos 0 3 9 1 9 2
## Caducifolios 0 0 3 1 4 1
## Castaños 30 0 2 0 0 0
## Eucalipto 0 10 0 0 3 0
## Matorral 3 0 27 0 3 1
## Pinsapos 0 1 2 7 1 0
## Quercineas 0 1 2 2 41 1
## Suelos 0 0 4 1 1 6
## Veg. Dispersa 0 0 14 2 3 7
## Veg. Ribera 1 0 1 2 11 0
## Veg. Dispersa Veg. Ribera class.error
## Algarrobos 0 0 0.7000000
## Bosque Coniferas 12 1 0.3650000
## Bosques Mixtos 7 3 0.5250000
## Caducifolios 16 1 0.7500000
## Castaños 1 1 0.2500000
## Eucalipto 1 1 0.7500000
## Matorral 18 0 0.6625000
## Pinsapos 8 2 0.8250000
## Quercineas 8 8 0.4875000
## Suelos 14 0 0.8500000
## Veg. Dispersa 61 0 0.4916667
## Veg. Ribera 0 17 0.5750000
rf_varImp_v <- varImp(rf_model_v, compete = FALSE)
plot(rf_varImp_v)
realizaremos un control de calidad.
pred_rf_v <- predict(rf_model_v$finalModel,
newdata = testing_v)
confusionMatrix(data = pred_rf_v, testing_v$Leyenda2)
## Confusion Matrix and Statistics
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 5 0 0 0
## Bosque Coniferas 1 31 6 0
## Bosques Mixtos 2 7 10 0
## Caducifolios 0 0 0 7
## Castaños 0 1 0 0
## Eucalipto 0 1 0 0
## Matorral 1 1 3 0
## Pinsapos 0 1 2 0
## Quercineas 0 1 1 0
## Suelos 1 0 1 0
## Veg. Dispersa 0 7 6 3
## Veg. Ribera 0 0 1 0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 0 1 0 0 0
## Bosque Coniferas 1 4 4 2 4 3
## Bosques Mixtos 0 1 3 3 1 1
## Caducifolios 0 0 0 1 0 0
## Castaños 9 0 0 0 0 0
## Eucalipto 0 2 0 0 0 0
## Matorral 0 0 8 0 1 1
## Pinsapos 0 0 1 1 1 0
## Quercineas 0 0 0 2 10 0
## Suelos 0 2 0 0 0 1
## Veg. Dispersa 0 0 3 1 2 4
## Veg. Ribera 0 1 0 0 1 0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0 0
## Bosque Coniferas 1 2
## Bosques Mixtos 3 1
## Caducifolios 4 0
## Castaños 0 0
## Eucalipto 0 0
## Matorral 2 0
## Pinsapos 0 0
## Quercineas 1 2
## Suelos 3 0
## Veg. Dispersa 16 0
## Veg. Ribera 0 5
##
## Overall Statistics
##
## Accuracy : 0.4773
## 95% CI : (0.4097, 0.5455)
## No Information Rate : 0.2273
## P-Value [Acc > NIR] : 3.84e-16
##
## Kappa : 0.3979
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: Algarrobos Class: Bosque Coniferas
## Sensitivity 0.50000 0.6200
## Specificity 0.99524 0.8353
## Pos Pred Value 0.83333 0.5254
## Neg Pred Value 0.97664 0.8820
## Prevalence 0.04545 0.2273
## Detection Rate 0.02273 0.1409
## Detection Prevalence 0.02727 0.2682
## Balanced Accuracy 0.74762 0.7276
## Class: Bosques Mixtos Class: Caducifolios Class: Castaños
## Sensitivity 0.33333 0.70000 0.90000
## Specificity 0.88421 0.97619 0.99524
## Pos Pred Value 0.31250 0.58333 0.90000
## Neg Pred Value 0.89362 0.98558 0.99524
## Prevalence 0.13636 0.04545 0.04545
## Detection Rate 0.04545 0.03182 0.04091
## Detection Prevalence 0.14545 0.05455 0.04545
## Balanced Accuracy 0.60877 0.83810 0.94762
## Class: Eucalipto Class: Matorral Class: Pinsapos
## Sensitivity 0.200000 0.40000 0.100000
## Specificity 0.995238 0.95500 0.976190
## Pos Pred Value 0.666667 0.47059 0.166667
## Neg Pred Value 0.963134 0.94089 0.957944
## Prevalence 0.045455 0.09091 0.045455
## Detection Rate 0.009091 0.03636 0.004545
## Detection Prevalence 0.013636 0.07727 0.027273
## Balanced Accuracy 0.597619 0.67750 0.538095
## Class: Quercineas Class: Suelos Class: Veg. Dispersa
## Sensitivity 0.50000 0.100000 0.53333
## Specificity 0.96500 0.966667 0.86316
## Pos Pred Value 0.58824 0.125000 0.38095
## Neg Pred Value 0.95074 0.957547 0.92135
## Prevalence 0.09091 0.045455 0.13636
## Detection Rate 0.04545 0.004545 0.07273
## Detection Prevalence 0.07727 0.036364 0.19091
## Balanced Accuracy 0.73250 0.533333 0.69825
## Class: Veg. Ribera
## Sensitivity 0.50000
## Specificity 0.98571
## Pos Pred Value 0.62500
## Neg Pred Value 0.97642
## Prevalence 0.04545
## Detection Rate 0.02273
## Detection Prevalence 0.03636
## Balanced Accuracy 0.74286
El objetivo es obtener una clasificación de la misma zona de estudio que en el tutorial 1 pero en este caso considerando datos multitemporales correspondientes a tres escenas de Sentinel 2: primeravera, verano y otoño.
#Otoño
plotRGB(sentinel_o,r=7,g=2,b=3,stretch="lin")
#Primavera
plotRGB(sentinel_p,r=7,g=2,b=3,stretch="lin")
#Verano
plotRGB(sentinel_v,r=7,g=2,b=3,stretch="lin")
Crearemos a continuación un rasterstack resultante de las escenas Sentinel 2 de las tres fechas, teniendo un total de 30 bandas espectrales (10 por cada una de las fechas)
sentinel <- stack(sentinel_o,sentinel_p,sentinel_v)
A partir de aquí, el desarrollo del clasificador será exactamente igual que en el caso de trabajar con una imagen, salvo que el tiempo de procesado será mayor.
#puntos.ref<- as_Spatial(puntos.ref)
puntos.ref@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
R.Forest<- superClass(sentinel,
trainData = puntos.ref,
trainPartition =0.5,
responseCol = "Leyenda2",
model = "rf")
leyenda_colores <- viridis::viridis(13)
plot(R.Forest$map,
col=leyenda_colores,
legend = FALSE)
legend("topright",cex=0.65, y.intersp = 0.55,x.intersp = 0.5,
legend = levels(as.factor(puntos.ref$Leyenda2)),
fill = leyenda_colores ,title = "",
inset=c(0,0))
Evaluación de la calidad temática:
R.Forest$modelFit
## [[1]]
## TrainAccuracy TrainKappa method
## 1 0.4750934 0.3857708 rf
##
## [[2]]
## Cross-Validated (5 fold) Confusion Matrix
##
## (entries are average cell counts across resamples)
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 1.4 0.2 0.2 0.0
## Bosque Coniferas 2.2 17.0 6.6 0.2
## Bosques Mixtos 0.0 3.2 3.6 0.4
## Caducifolios 0.0 0.2 0.2 1.0
## Castaños 0.0 0.0 0.2 0.0
## Eucalipto 0.2 0.8 0.0 0.0
## Matorral 0.8 0.2 0.6 0.2
## Pinsapos 0.0 0.8 0.2 0.4
## Quercineas 0.0 0.6 1.2 0.2
## Suelos 0.0 0.4 0.2 0.0
## Veg. Dispersa 0.0 1.4 1.0 2.6
## Veg. Ribera 0.0 0.2 0.2 0.0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0.0 0.4 0.4 0.0 0.2 0.0
## Bosque Coniferas 0.2 3.2 1.2 1.6 1.4 1.2
## Bosques Mixtos 0.0 0.2 0.6 0.4 1.2 0.6
## Caducifolios 0.0 0.0 0.2 0.2 0.2 0.2
## Castaños 4.4 0.0 0.2 0.0 0.0 0.0
## Eucalipto 0.0 1.0 0.0 0.0 0.2 0.0
## Matorral 0.0 0.0 5.2 0.0 0.2 0.2
## Pinsapos 0.0 0.0 0.0 2.0 0.0 0.2
## Quercineas 0.0 0.0 0.0 0.2 4.8 0.0
## Suelos 0.0 0.0 0.0 0.4 0.0 1.4
## Veg. Dispersa 0.0 0.0 2.2 0.2 1.2 1.2
## Veg. Ribera 0.0 0.2 0.0 0.0 0.6 0.0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0.2 0.0
## Bosque Coniferas 3.8 1.0
## Bosques Mixtos 0.4 1.0
## Caducifolios 0.6 0.0
## Castaños 0.2 0.0
## Eucalipto 0.0 0.2
## Matorral 1.4 0.0
## Pinsapos 0.0 0.0
## Quercineas 0.4 0.6
## Suelos 0.2 0.0
## Veg. Dispersa 7.8 0.2
## Veg. Ribera 0.0 1.8
##
## Accuracy (average) : 0.475
R.Forest$model$results
## mtry Accuracy Kappa AccuracySD KappaSD
## 1 2 0.4584268 0.3614611 0.02263369 0.02747087
## 2 16 0.4658172 0.3745458 0.03393721 0.04092720
## 3 30 0.4750934 0.3857708 0.04023238 0.05107661
reflectancia<- as.data.frame(raster::extract(sentinel,puntos.ref))
train_data = as_Spatial(puntos.ref_backup)
train_data@data$Leyenda2=as.factor(puntos.ref@data$Leyenda2)
train_data@data=data.frame(train_data@data,reflectancia[match(rownames(train_data@data),rownames(reflectancia)),])
Veamos el resultado obtenido.
str(train_data)
## Formal class 'SpatialPointsDataFrame' [package "sp"] with 5 slots
## ..@ data :'data.frame': 1100 obs. of 35 variables:
## .. ..$ OBJECTID : num [1:1100] 1 1 1 1 1 1 1 1 1 1 ...
## .. ..$ NOM_FORARB : chr [1:1100] "Alcornocales" "Alcornocales" "Alcornocales" "Alcornocales" ...
## .. ..$ Shape_Leng : num [1:1100] 34046 34046 34046 34046 34046 ...
## .. ..$ Shape_Area : num [1:1100] 4419619 4419619 4419619 4419619 4419619 ...
## .. ..$ Leyenda2 : Factor w/ 12 levels "Algarrobos","Bosque Coniferas",..: 9 9 9 9 9 9 9 9 9 9 ...
## .. ..$ sentinel_o_b01: num [1:1100] 935 1069 869 875 922 ...
## .. ..$ sentinel_o_b02: num [1:1100] 701 871 562 583 681 696 609 753 500 654 ...
## .. ..$ sentinel_o_b03: num [1:1100] 434 703 356 360 469 471 377 542 282 391 ...
## .. ..$ sentinel_o_b04: num [1:1100] 684 985 456 454 694 702 477 791 254 562 ...
## .. ..$ sentinel_o_b05: num [1:1100] 1405 2058 800 843 1312 ...
## .. ..$ sentinel_o_b06: num [1:1100] 1705 2270 962 853 1720 ...
## .. ..$ sentinel_o_b07: num [1:1100] 1545 2263 787 901 1605 ...
## .. ..$ sentinel_o_b08: num [1:1100] 1754 2531 883 1032 1697 ...
## .. ..$ sentinel_o_b09: num [1:1100] 689 1983 497 755 1248 ...
## .. ..$ sentinel_o_b10: num [1:1100] 340 1174 258 333 698 ...
## .. ..$ sentinel_p_b01: num [1:1100] 888 879 797 812 826 832 859 806 778 806 ...
## .. ..$ sentinel_p_b02: num [1:1100] 766 774 657 647 674 703 716 656 596 672 ...
## .. ..$ sentinel_p_b03: num [1:1100] 576 607 452 417 463 497 491 440 380 473 ...
## .. ..$ sentinel_p_b04: num [1:1100] 842 949 674 637 761 767 768 700 595 747 ...
## .. ..$ sentinel_p_b05: num [1:1100] 1607 1903 1560 1653 1453 ...
## .. ..$ sentinel_p_b06: num [1:1100] 1785 2197 1783 1993 1666 ...
## .. ..$ sentinel_p_b07: num [1:1100] 1756 2237 1800 1968 1675 ...
## .. ..$ sentinel_p_b08: num [1:1100] 1922 2383 2040 2119 1839 ...
## .. ..$ sentinel_p_b09: num [1:1100] 1127 1706 1176 1181 1246 ...
## .. ..$ sentinel_p_b10: num [1:1100] 618 955 612 547 643 788 668 608 385 680 ...
## .. ..$ sentinel_v_b01: num [1:1100] 868 933 920 873 870 871 847 900 824 877 ...
## .. ..$ sentinel_v_b02: num [1:1100] 779 849 844 783 756 776 742 819 722 791 ...
## .. ..$ sentinel_v_b03: num [1:1100] 573 768 797 632 627 650 545 700 527 668 ...
## .. ..$ sentinel_v_b04: num [1:1100] 834 998 997 899 866 900 793 970 774 936 ...
## .. ..$ sentinel_v_b05: num [1:1100] 1511 1533 1506 1685 1446 ...
## .. ..$ sentinel_v_b06: num [1:1100] 1739 1811 1716 2013 1649 ...
## .. ..$ sentinel_v_b07: num [1:1100] 1642 1736 1676 1972 1678 ...
## .. ..$ sentinel_v_b08: num [1:1100] 1902 1984 1961 2204 1925 ...
## .. ..$ sentinel_v_b09: num [1:1100] 1007 1746 1406 1436 1404 ...
## .. ..$ sentinel_v_b10: num [1:1100] 487 997 792 640 736 802 530 833 446 602 ...
## ..@ coords.nrs : num(0)
## ..@ coords : num [1:1100, 1:2] 326741 329242 328773 331246 329865 ...
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : NULL
## .. .. ..$ : chr [1:2] "lon" "lat"
## ..@ bbox : num [1:2, 1:2] 312560 4052227 331754 4072825
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : chr [1:2] "lon" "lat"
## .. .. ..$ : chr [1:2] "min" "max"
## ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
## .. .. ..@ projargs: chr "+proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
## .. .. ..$ comment: chr "PROJCRS[\"ETRS89 / UTM zone 30N\",\n BASEGEOGCRS[\"ETRS89\",\n DATUM[\"European Terrestrial Reference"| __truncated__
resumen estadístico de la variable:
summary(train_data@data)
## OBJECTID NOM_FORARB Shape_Leng Shape_Area
## Min. : 1.0 Length:1100 Min. : 1805 Min. : 52512
## 1st Qu.: 6.0 Class :character 1st Qu.: 3900 1st Qu.: 84213
## Median :11.5 Mode :character Median : 26445 Median : 2351264
## Mean :11.5 Mean : 64448 Mean : 9131237
## 3rd Qu.:17.0 3rd Qu.: 80456 3rd Qu.:10093586
## Max. :22.0 Max. :455519 Max. :81665992
##
## Leyenda2 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## Bosque Coniferas:250 Min. : 761 Min. : 457.0 Min. : 249.0
## Bosques Mixtos :150 1st Qu.: 888 1st Qu.: 632.8 1st Qu.: 408.0
## Veg. Dispersa :150 Median : 980 Median : 787.5 Median : 587.5
## Matorral :100 Mean :1103 Mean : 905.1 Mean : 775.2
## Quercineas :100 3rd Qu.:1126 3rd Qu.: 995.2 3rd Qu.: 963.2
## Algarrobos : 50 Max. :5384 Max. :5290.0 Max. :5925.0
## (Other) :300
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## Min. : 226.0 Min. : 247 Min. : 233 Min. : 212 Min. : 187
## 1st Qu.: 561.5 1st Qu.:1030 1st Qu.:1158 1st Qu.:1146 1st Qu.:1234
## Median : 849.0 Median :1566 Median :1770 Median :1766 Median :1918
## Mean : 979.8 Mean :1561 Mean :1737 Mean :1732 Mean :1869
## 3rd Qu.:1241.5 3rd Qu.:2002 3rd Qu.:2242 3rd Qu.:2275 3rd Qu.:2448
## Max. :6146.0 Max. :6331 Max. :6394 Max. :6354 Max. :6308
##
## sentinel_o_b09 sentinel_o_b10 sentinel_p_b01 sentinel_p_b02
## Min. : 53.0 Min. : 28.0 Min. : 723.0 Min. : 509.0
## 1st Qu.: 600.5 1st Qu.: 309.2 1st Qu.: 845.8 1st Qu.: 711.0
## Median :1121.0 Median : 639.0 Median : 928.0 Median : 827.0
## Mean :1300.0 Mean : 834.0 Mean : 996.2 Mean : 907.4
## 3rd Qu.:1829.5 3rd Qu.:1186.0 3rd Qu.:1099.0 3rd Qu.:1056.2
## Max. :5973.0 Max. :4484.0 Max. :1962.0 Max. :2084.0
##
## sentinel_p_b03 sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07
## Min. : 324.0 Min. : 430.0 Min. : 729 Min. : 761 Min. : 613
## 1st Qu.: 522.8 1st Qu.: 794.2 1st Qu.:1513 1st Qu.:1722 1st Qu.:1705
## Median : 697.5 Median : 980.0 Median :1745 Median :1965 Median :1958
## Mean : 816.8 Mean :1084.9 Mean :1772 Mean :1989 Mean :1993
## 3rd Qu.:1026.0 3rd Qu.:1297.0 3rd Qu.:2000 3rd Qu.:2221 3rd Qu.:2238
## Max. :2295.0 Max. :2584.0 Max. :3219 Max. :3571 Max. :3714
##
## sentinel_p_b08 sentinel_p_b09 sentinel_p_b10 sentinel_v_b01
## Min. : 724 Min. : 494 Min. : 264.0 Min. : 786.0
## 1st Qu.:1852 1st Qu.:1216 1st Qu.: 679.8 1st Qu.: 892.0
## Median :2129 Median :1580 Median : 987.5 Median : 966.5
## Mean :2155 Mean :1739 Mean :1145.3 Mean :1017.3
## 3rd Qu.:2412 3rd Qu.:2160 3rd Qu.:1483.0 3rd Qu.:1088.2
## Max. :4126 Max. :4883 Max. :3668.0 Max. :1776.0
##
## sentinel_v_b02 sentinel_v_b03 sentinel_v_b04 sentinel_v_b05
## Min. : 639.0 Min. : 471.0 Min. : 629.0 Min. : 888
## 1st Qu.: 815.8 1st Qu.: 691.8 1st Qu.: 935.8 1st Qu.:1520
## Median : 928.0 Median : 883.0 Median :1131.0 Median :1744
## Mean : 987.6 Mean : 981.8 Mean :1199.3 Mean :1758
## 3rd Qu.:1093.0 3rd Qu.:1167.8 3rd Qu.:1378.0 3rd Qu.:1952
## Max. :1883.0 Max. :2379.0 Max. :2539.0 Max. :2895
##
## sentinel_v_b06 sentinel_v_b07 sentinel_v_b08 sentinel_v_b09 sentinel_v_b10
## Min. :1121 Min. :1036 Min. :1250 Min. : 651 Min. : 320
## 1st Qu.:1749 1st Qu.:1690 1st Qu.:1928 1st Qu.:1302 1st Qu.: 689
## Median :2002 Median :1948 Median :2221 Median :1674 Median : 987
## Mean :2021 Mean :1967 Mean :2244 Mean :1811 Mean :1100
## 3rd Qu.:2262 3rd Qu.:2214 3rd Qu.:2520 3rd Qu.:2170 3rd Qu.:1357
## Max. :3210 Max. :3156 Max. :3658 Max. :4555 Max. :3242
##
No hay datos ausentes (NA).
hre_seed<- 123
set.seed(hre_seed)
inTraining <- createDataPartition(train_data_o@data$Leyenda2, p=0.80,list=FALSE)
training <-train_data@data[inTraining,]
training=training[,-(1:4)] #Borramos columnas no necesarias
testing <- train_data@data[-inTraining,]
testing=testing[,-(1:4)] #Borramos columnas no necesarias
summary(training)
## Leyenda2 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## Bosque Coniferas:200 Min. : 761.0 Min. : 457.0 Min. : 249.0
## Bosques Mixtos :120 1st Qu.: 883.0 1st Qu.: 626.8 1st Qu.: 402.8
## Veg. Dispersa :120 Median : 976.5 Median : 781.0 Median : 584.5
## Matorral : 80 Mean :1103.7 Mean : 902.4 Mean : 769.8
## Quercineas : 80 3rd Qu.:1126.0 3rd Qu.: 994.0 3rd Qu.: 955.5
## Algarrobos : 40 Max. :5384.0 Max. :5290.0 Max. :5925.0
## (Other) :240
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## Min. : 226.0 Min. : 247 Min. : 244 Min. : 214 Min. : 187
## 1st Qu.: 551.2 1st Qu.:1015 1st Qu.:1129 1st Qu.:1118 1st Qu.:1187
## Median : 845.5 Median :1540 Median :1721 Median :1742 Median :1896
## Mean : 970.3 Mean :1542 Mean :1714 Mean :1705 Mean :1842
## 3rd Qu.:1230.5 3rd Qu.:1984 3rd Qu.:2223 3rd Qu.:2246 3rd Qu.:2416
## Max. :6146.0 Max. :6331 Max. :6394 Max. :6354 Max. :6308
##
## sentinel_o_b09 sentinel_o_b10 sentinel_p_b01 sentinel_p_b02
## Min. : 59.0 Min. : 29.0 Min. : 723.0 Min. : 509.0
## 1st Qu.: 573.5 1st Qu.: 300.0 1st Qu.: 845.0 1st Qu.: 709.8
## Median :1113.5 Median : 632.5 Median : 932.5 Median : 830.5
## Mean :1259.2 Mean : 804.5 Mean : 993.3 Mean : 902.6
## 3rd Qu.:1799.2 3rd Qu.:1153.0 3rd Qu.:1099.5 3rd Qu.:1052.2
## Max. :5103.0 Max. :3795.0 Max. :1793.0 Max. :1804.0
##
## sentinel_p_b03 sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07
## Min. : 324.0 Min. : 430 Min. : 729 Min. : 761 Min. : 613
## 1st Qu.: 522.8 1st Qu.: 789 1st Qu.:1514 1st Qu.:1718 1st Qu.:1705
## Median : 701.0 Median : 986 Median :1745 Median :1964 Median :1955
## Mean : 811.4 Mean :1077 Mean :1759 Mean :1975 Mean :1978
## 3rd Qu.:1026.0 3rd Qu.:1296 3rd Qu.:1991 3rd Qu.:2210 3rd Qu.:2227
## Max. :2031.0 Max. :2508 Max. :3185 Max. :3513 Max. :3614
##
## sentinel_p_b08 sentinel_p_b09 sentinel_p_b10 sentinel_v_b01
## Min. : 724 Min. : 494 Min. : 264.0 Min. : 786.0
## 1st Qu.:1850 1st Qu.:1205 1st Qu.: 678.8 1st Qu.: 892.8
## Median :2124 Median :1610 Median : 993.5 Median : 965.0
## Mean :2140 Mean :1727 Mean :1136.7 Mean :1013.2
## 3rd Qu.:2397 3rd Qu.:2160 3rd Qu.:1484.0 3rd Qu.:1089.2
## Max. :3872 Max. :4002 Max. :2939.0 Max. :1684.0
##
## sentinel_v_b02 sentinel_v_b03 sentinel_v_b04 sentinel_v_b05 sentinel_v_b06
## Min. : 639.0 Min. : 471.0 Min. : 629 Min. : 888 Min. :1121
## 1st Qu.: 814.0 1st Qu.: 689.0 1st Qu.: 935 1st Qu.:1520 1st Qu.:1748
## Median : 926.5 Median : 881.5 Median :1132 Median :1747 Median :2001
## Mean : 982.5 Mean : 972.8 Mean :1191 Mean :1753 Mean :2015
## 3rd Qu.:1093.0 3rd Qu.:1167.8 3rd Qu.:1374 3rd Qu.:1948 3rd Qu.:2260
## Max. :1823.0 Max. :2335.0 Max. :2436 Max. :2789 Max. :3058
##
## sentinel_v_b07 sentinel_v_b08 sentinel_v_b09 sentinel_v_b10
## Min. :1036 Min. :1250 Min. : 651 Min. : 320
## 1st Qu.:1690 1st Qu.:1929 1st Qu.:1295 1st Qu.: 686
## Median :1944 Median :2216 Median :1678 Median : 987
## Mean :1960 Mean :2236 Mean :1795 Mean :1088
## 3rd Qu.:2206 3rd Qu.:2516 3rd Qu.:2169 3rd Qu.:1350
## Max. :2929 Max. :3334 Max. :4057 Max. :2886
##
summary(testing)
## Leyenda2 sentinel_o_b01 sentinel_o_b02 sentinel_o_b03
## Bosque Coniferas:50 Min. : 781.0 Min. : 470.0 Min. : 257.0
## Bosques Mixtos :30 1st Qu.: 898.8 1st Qu.: 658.5 1st Qu.: 430.5
## Veg. Dispersa :30 Median : 995.0 Median : 802.0 Median : 608.0
## Matorral :20 Mean :1098.6 Mean : 915.9 Mean : 797.1
## Quercineas :20 3rd Qu.:1126.0 3rd Qu.: 999.0 3rd Qu.: 990.0
## Algarrobos :10 Max. :2828.0 Max. :2594.0 Max. :2623.0
## (Other) :60
## sentinel_o_b04 sentinel_o_b05 sentinel_o_b06 sentinel_o_b07 sentinel_o_b08
## Min. : 230 Min. : 278 Min. : 233 Min. : 212 Min. : 197
## 1st Qu.: 610 1st Qu.:1175 1st Qu.:1330 1st Qu.:1270 1st Qu.:1355
## Median : 876 Median :1646 Median :1852 Median :1858 Median :1983
## Mean :1018 Mean :1638 Mean :1827 Mean :1839 Mean :1978
## 3rd Qu.:1273 3rd Qu.:2054 3rd Qu.:2351 3rd Qu.:2402 3rd Qu.:2568
## Max. :2985 Max. :3614 Max. :3895 Max. :4144 Max. :4573
##
## sentinel_o_b09 sentinel_o_b10 sentinel_p_b01 sentinel_p_b02
## Min. : 53 Min. : 28.0 Min. : 725.0 Min. : 518.0
## 1st Qu.: 727 1st Qu.: 370.8 1st Qu.: 850.8 1st Qu.: 722.8
## Median :1156 Median : 667.5 Median : 923.5 Median : 812.5
## Mean :1463 Mean : 952.2 Mean :1008.0 Mean : 926.7
## 3rd Qu.:2166 3rd Qu.:1397.0 3rd Qu.:1085.0 3rd Qu.:1065.8
## Max. :5973 Max. :4484.0 Max. :1962.0 Max. :2084.0
##
## sentinel_p_b03 sentinel_p_b04 sentinel_p_b05 sentinel_p_b06 sentinel_p_b07
## Min. : 327.0 Min. : 447.0 Min. : 886 Min. : 945 Min. :1009
## 1st Qu.: 527.2 1st Qu.: 810.8 1st Qu.:1512 1st Qu.:1730 1st Qu.:1691
## Median : 666.5 Median : 960.0 Median :1739 Median :1971 Median :1974
## Mean : 838.4 Mean :1114.5 Mean :1821 Mean :2044 Mean :2049
## 3rd Qu.:1031.2 3rd Qu.:1378.2 3rd Qu.:2038 3rd Qu.:2274 3rd Qu.:2314
## Max. :2295.0 Max. :2584.0 Max. :3219 Max. :3571 Max. :3714
##
## sentinel_p_b08 sentinel_p_b09 sentinel_p_b10 sentinel_v_b01
## Min. : 996 Min. : 530 Min. : 282.0 Min. : 813.0
## 1st Qu.:1855 1st Qu.:1240 1st Qu.: 689.8 1st Qu.: 892.0
## Median :2148 Median :1516 Median : 932.0 Median : 976.5
## Mean :2215 Mean :1790 Mean :1180.1 Mean :1033.5
## 3rd Qu.:2472 3rd Qu.:2159 3rd Qu.:1468.0 3rd Qu.:1087.0
## Max. :4126 Max. :4883 Max. :3668.0 Max. :1776.0
##
## sentinel_v_b02 sentinel_v_b03 sentinel_v_b04 sentinel_v_b05
## Min. : 706.0 Min. : 527.0 Min. : 723.0 Min. :1075
## 1st Qu.: 818.8 1st Qu.: 700.5 1st Qu.: 942.5 1st Qu.:1520
## Median : 937.0 Median : 905.5 Median :1124.5 Median :1727
## Mean :1007.8 Mean :1017.6 Mean :1231.0 Mean :1781
## 3rd Qu.:1097.5 3rd Qu.:1166.2 3rd Qu.:1383.2 3rd Qu.:1969
## Max. :1883.0 Max. :2379.0 Max. :2539.0 Max. :2895
##
## sentinel_v_b06 sentinel_v_b07 sentinel_v_b08 sentinel_v_b09 sentinel_v_b10
## Min. :1292 Min. :1121 Min. :1409 Min. : 859 Min. : 470.0
## 1st Qu.:1754 1st Qu.:1694 1st Qu.:1926 1st Qu.:1330 1st Qu.: 716.8
## Median :2009 Median :1985 Median :2248 Median :1672 Median : 980.0
## Mean :2044 Mean :1993 Mean :2274 Mean :1875 Mean :1148.8
## 3rd Qu.:2280 3rd Qu.:2232 3rd Qu.:2534 3rd Qu.:2181 3rd Qu.:1371.8
## Max. :3210 Max. :3156 Max. :3658 Max. :4555 Max. :3242.0
##
featurePlot(x=training[,2:11],
y=training$Leyenda2,
plot="density",
labels=c("Reflectancia","Distribucion densidades"),
layout=c(2,2))
skwenessvalues <- apply(training[,2:11],2,skewness)
skwenessvalues
## sentinel_o_b01 sentinel_o_b02 sentinel_o_b03 sentinel_o_b04 sentinel_o_b05
## 4.8662829 4.1051162 3.5583089 2.8626734 1.1915328
## sentinel_o_b06 sentinel_o_b07 sentinel_o_b08 sentinel_o_b09 sentinel_o_b10
## 0.7588326 0.6919157 0.4820169 0.8648015 1.1799476
featurePlot(x=training[,2:11],
y=training$Leyenda2,
plot="box",
layout=c(2,2))
rf_model<-train(Leyenda2~.,data=training, method="rf",
trControl=fitControl,
prox=TRUE,
fitBest = FALSE,
returnData = TRUE)
print(rf_model)
## Random Forest
##
## 880 samples
## 30 predictor
## 12 classes: 'Algarrobos', 'Bosque Coniferas', 'Bosques Mixtos', 'Caducifolios', 'Castaños', 'Eucalipto', 'Matorral', 'Pinsapos', 'Quercineas', 'Suelos', 'Veg. Dispersa', 'Veg. Ribera'
##
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 5 times)
## Summary of sample sizes: 704, 704, 704, 704, 704, 704, ...
## Resampling results across tuning parameters:
##
## mtry Accuracy Kappa
## 2 0.5206818 0.4392291
## 16 0.5350000 0.4598849
## 30 0.5293182 0.4534551
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 16.
plot(rf_model)
rf_model$finalModel
##
## Call:
## randomForest(x = x, y = y, mtry = min(param$mtry, ncol(x)), proximity = TRUE, fitBest = FALSE, returnData = TRUE)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 16
##
## OOB estimate of error rate: 44.09%
## Confusion matrix:
## Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 22 12 3 0
## Bosque Coniferas 3 155 14 1
## Bosques Mixtos 0 30 61 2
## Caducifolios 0 2 2 13
## Castaños 0 0 0 0
## Eucalipto 1 20 3 0
## Matorral 5 12 10 1
## Pinsapos 0 15 3 0
## Quercineas 1 12 6 2
## Suelos 1 8 7 2
## Veg. Dispersa 1 14 5 11
## Veg. Ribera 1 6 4 0
## Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 0 3 0 0 0
## Bosque Coniferas 0 7 2 5 5 3
## Bosques Mixtos 0 1 3 3 11 1
## Caducifolios 0 2 3 0 1 1
## Castaños 38 0 1 0 0 0
## Eucalipto 0 12 0 0 1 0
## Matorral 0 1 39 1 0 0
## Pinsapos 0 2 1 13 3 0
## Quercineas 0 4 0 0 42 0
## Suelos 0 0 5 3 0 1
## Veg. Dispersa 0 2 3 1 3 2
## Veg. Ribera 1 0 2 0 8 0
## Veg. Dispersa Veg. Ribera class.error
## Algarrobos 0 0 0.4500000
## Bosque Coniferas 5 0 0.2250000
## Bosques Mixtos 8 0 0.4916667
## Caducifolios 15 1 0.6750000
## Castaños 1 0 0.0500000
## Eucalipto 0 3 0.7000000
## Matorral 11 0 0.5125000
## Pinsapos 3 0 0.6750000
## Quercineas 10 3 0.4750000
## Suelos 13 0 0.9750000
## Veg. Dispersa 78 0 0.3500000
## Veg. Ribera 0 18 0.5500000
rf_varImp <- varImp(rf_model, compete = FALSE)
plot(rf_varImp)
Realizaremos un control de calidad.
pred_rf <- predict(rf_model$finalModel,
newdata = testing)
confusionMatrix(data = pred_rf, testing$Leyenda2)
## Confusion Matrix and Statistics
##
## Reference
## Prediction Algarrobos Bosque Coniferas Bosques Mixtos Caducifolios
## Algarrobos 4 0 0 1
## Bosque Coniferas 5 36 9 0
## Bosques Mixtos 0 8 10 2
## Caducifolios 0 1 0 2
## Castaños 0 0 0 0
## Eucalipto 0 0 1 0
## Matorral 0 1 5 0
## Pinsapos 0 0 1 1
## Quercineas 0 2 2 0
## Suelos 0 0 0 0
## Veg. Dispersa 1 2 2 4
## Veg. Ribera 0 0 0 0
## Reference
## Prediction Castaños Eucalipto Matorral Pinsapos Quercineas Suelos
## Algarrobos 0 0 0 0 0 0
## Bosque Coniferas 0 6 2 5 2 1
## Bosques Mixtos 1 1 4 0 2 4
## Caducifolios 0 0 0 0 0 0
## Castaños 9 0 0 0 0 0
## Eucalipto 0 2 0 0 0 0
## Matorral 0 1 10 0 1 0
## Pinsapos 0 0 0 3 0 2
## Quercineas 0 0 0 1 12 0
## Suelos 0 0 1 0 0 1
## Veg. Dispersa 0 0 3 1 3 2
## Veg. Ribera 0 0 0 0 0 0
## Reference
## Prediction Veg. Dispersa Veg. Ribera
## Algarrobos 0 0
## Bosque Coniferas 5 1
## Bosques Mixtos 3 0
## Caducifolios 2 0
## Castaños 0 0
## Eucalipto 1 1
## Matorral 1 0
## Pinsapos 1 0
## Quercineas 1 2
## Suelos 1 0
## Veg. Dispersa 15 0
## Veg. Ribera 0 6
##
## Overall Statistics
##
## Accuracy : 0.5
## 95% CI : (0.432, 0.568)
## No Information Rate : 0.2273
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.4178
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: Algarrobos Class: Bosque Coniferas
## Sensitivity 0.40000 0.7200
## Specificity 0.99524 0.7882
## Pos Pred Value 0.80000 0.5000
## Neg Pred Value 0.97209 0.9054
## Prevalence 0.04545 0.2273
## Detection Rate 0.01818 0.1636
## Detection Prevalence 0.02273 0.3273
## Balanced Accuracy 0.69762 0.7541
## Class: Bosques Mixtos Class: Caducifolios Class: Castaños
## Sensitivity 0.33333 0.200000 0.90000
## Specificity 0.86842 0.985714 1.00000
## Pos Pred Value 0.28571 0.400000 1.00000
## Neg Pred Value 0.89189 0.962791 0.99526
## Prevalence 0.13636 0.045455 0.04545
## Detection Rate 0.04545 0.009091 0.04091
## Detection Prevalence 0.15909 0.022727 0.04091
## Balanced Accuracy 0.60088 0.592857 0.95000
## Class: Eucalipto Class: Matorral Class: Pinsapos
## Sensitivity 0.200000 0.50000 0.30000
## Specificity 0.985714 0.95500 0.97619
## Pos Pred Value 0.400000 0.52632 0.37500
## Neg Pred Value 0.962791 0.95025 0.96698
## Prevalence 0.045455 0.09091 0.04545
## Detection Rate 0.009091 0.04545 0.01364
## Detection Prevalence 0.022727 0.08636 0.03636
## Balanced Accuracy 0.592857 0.72750 0.63810
## Class: Quercineas Class: Suelos Class: Veg. Dispersa
## Sensitivity 0.60000 0.100000 0.50000
## Specificity 0.96000 0.990476 0.90526
## Pos Pred Value 0.60000 0.333333 0.45455
## Neg Pred Value 0.96000 0.958525 0.91979
## Prevalence 0.09091 0.045455 0.13636
## Detection Rate 0.05455 0.004545 0.06818
## Detection Prevalence 0.09091 0.013636 0.15000
## Balanced Accuracy 0.78000 0.545238 0.70263
## Class: Veg. Ribera
## Sensitivity 0.60000
## Specificity 1.00000
## Pos Pred Value 1.00000
## Neg Pred Value 0.98131
## Prevalence 0.04545
## Detection Rate 0.02727
## Detection Prevalence 0.02727
## Balanced Accuracy 0.80000